Skip to main content

Async-only SQLAlchemy 2.x mixins with statement-based query helpers

Project description

sqlalchemy-mixins-async

sqlalchemy-mixins-async is the async-only SQLAlchemy 2.x variant, published under a separate package name so it can coexist with the older sqlalchemy-mixins project.

What changed in v3

  • AsyncSession / async_sessionmaker only
  • select()-first query building
  • async CRUD helpers on models
  • Django-like filter and sort DSL preserved on top of Select
  • selectinload is the default eager-loading recommendation

Sync Session.query() patterns and sync tests/examples were removed.

Installation

uv add sqlalchemy-mixins-async

Built-in test coverage uses sqlite+aiosqlite. PostgreSQL and MySQL drivers are optional:

uv add 'sqlalchemy-mixins-async[asyncpg]'
uv add 'sqlalchemy-mixins-async[aiomysql]'
uv add 'sqlalchemy-mixins-async[all]'

Quick start

from sqlalchemy import ForeignKey
from sqlalchemy.ext.asyncio import AsyncAttrs, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

from sqlalchemy_mixins_async import ActiveRecordMixin, QueryMixin


class Base(AsyncAttrs, DeclarativeBase):
    pass


class BaseModel(Base, ActiveRecordMixin, QueryMixin):
    __abstract__ = True


class User(BaseModel):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    posts: Mapped[list["Post"]] = relationship(back_populates="user", lazy="selectin")


class Post(BaseModel):
    __tablename__ = "posts"

    id: Mapped[int] = mapped_column(primary_key=True)
    body: Mapped[str]
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    user: Mapped[User] = relationship(back_populates="posts", lazy="selectin")


engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/app")
Session = async_sessionmaker(engine, expire_on_commit=False)
BaseModel.set_sessionmaker(Session)

user = await User.create(name="Bill")
post = await Post.create(body="hello", user_id=user.id)

stmt = Post.query(where={"user___name": "Bill"})
rows = await Post.all(stmt=stmt)

Supported async engines

  • PostgreSQL: postgresql+asyncpg://user:pass@host/db
  • SQLite: sqlite+aiosqlite:///path/to.db
  • MySQL/MariaDB: mysql+aiomysql://user:pass@host/db

Notes:

  • asyncpg gets first-class integrity error translation into library exceptions such as AlreadyExistsError.
  • aiosqlite is the default lightweight backend used by the unit tests.
  • aiomysql is supported through SQLAlchemy's async MySQL dialect. On MySQL-family backends, server-side RETURNING behavior is more limited than PostgreSQL, so expire_on_commit=False and explicit refreshes remain the recommended pattern.

Main API

  • set_sessionmaker(async_sessionmaker)
  • await Model.create(...)
  • await instance.save()
  • await instance.update(...)
  • await instance.delete()
  • await Model.find(id)
  • await Model.find_or_fail(id)
  • await Model.all(stmt=...)
  • Model.query(where=..., order_by=..., load=...) -> Select
  • Model.where(...) -> Select
  • Model.order_by(...) -> Select
  • Model.with_(schema) -> Select
  • apply_query(stmt, where=..., order_by=..., load=...) -> Select
  • await Model.execute(stmt)
  • await Model.scalars(stmt)

Testing

uv sync --group dev
uv run python -m unittest discover sqlalchemy_mixins_async/tests

The backend integration tests use testcontainers-python to start PostgreSQL and MySQL automatically. They run when Docker is available and skip cleanly when the daemon or container dependencies are missing.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlalchemy_mixins_async-3.0.0.tar.gz (20.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlalchemy_mixins_async-3.0.0-py3-none-any.whl (28.7 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_mixins_async-3.0.0.tar.gz.

File metadata

  • Download URL: sqlalchemy_mixins_async-3.0.0.tar.gz
  • Upload date:
  • Size: 20.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.27 {"installer":{"name":"uv","version":"0.9.27","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlalchemy_mixins_async-3.0.0.tar.gz
Algorithm Hash digest
SHA256 ae8fa88af910518841c9d761f041fc9c5e161b1c53ffe0225a4010349e9547fe
MD5 3836715ef9959b6ddecde96e8c5001a4
BLAKE2b-256 5a5ffe2813f7e30b437c475b2cb8e05a13f026d82b1b6ee3441d39cdc8730a0f

See more details on using hashes here.

File details

Details for the file sqlalchemy_mixins_async-3.0.0-py3-none-any.whl.

File metadata

  • Download URL: sqlalchemy_mixins_async-3.0.0-py3-none-any.whl
  • Upload date:
  • Size: 28.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.27 {"installer":{"name":"uv","version":"0.9.27","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlalchemy_mixins_async-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c219f620ceb92806851c167e15ea71278b7d63f7990a45a96f5543a11806f17c
MD5 5c0f9b56c51eab02f891e67fa1de1d19
BLAKE2b-256 6fa3aadfe0f185cd911666401ea423bb36e508a4ddc43d72d7ba03ae9c2e4b0d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page