Skip to content

sqlmodel-async-factory

sqlmodel-async-factory

factory_boy factories that build and persist SQLModel objects through an async session.

License: MIT Status: beta Python 3.10+


Documentation: https://sqlmodel-async-factory.businessagile.eu

Source Code: https://github.com/BiBzz/sqlmodel-async-factory

Created by: Alexandre BERREBI, maintained by Business Agile


sqlmodel-async-factory gives you factory_boy factories for SQLModel models that are saved through an async SQLAlchemy session, for test suites whose database access is async from end to end.

factory_boy ships SQLAlchemyModelFactory, which calls session.add() and session.commit() synchronously. Against an AsyncSession those calls either raise MissingGreenlet or silently never flush. AsyncSQLModelFactory keeps the whole factory_boy declaration language and makes the create step awaitable.

The key features are:

  • Awaitable create: await HeroFactory.create() and await HeroFactory.create_batch(3) return saved, committed instances.
  • The factory_boy you know: Sequence, LazyAttribute, Faker, traits and keyword overrides work unchanged.
  • SubFactory, handled once: a hero's team is created, committed and awaited before the hero is built, so the model receives an instance, never a pending task.
  • get_or_create: sqlalchemy_get_or_create reuses the existing row, looked up through AsyncSession.exec() so it returns model instances rather than rows.
  • Build without a database: build() and build_batch() stay synchronous and never touch the session.
  • Typed: the package ships its type information (py.typed).

Requirements

A currently supported version of Python: 3.10 or later.

factory_boy 3, SQLAlchemy 2 with its asyncio extra and SQLModel 0.0.25 or later. They are installed with it.

An async database driver for your database, such as asyncpg for PostgreSQL or aiosqlite for SQLite.

Installation

$ pip install sqlmodel-async-factory

or, with uv:

$ uv add --dev sqlmodel-async-factory

Example

The models

Two SQLModel tables, a team and its heroes, in models.py:

from sqlmodel import Field, Relationship, SQLModel


class Team(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str = Field(unique=True)
    headquarters: str

    heroes: list["Hero"] = Relationship(back_populates="team")


class Hero(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: int | None = None
    team_id: int | None = Field(default=None, foreign_key="team.id")

    team: Team | None = Relationship(
        back_populates="heroes", sa_relationship_kwargs={"lazy": "selectin"}
    )

The relationship a test reads back is loaded with selectin: under asyncio, an attribute cannot load itself lazily on first access. See session settings.

The factories

The factories, in factories.py, declare how to fill each field. Here the database is an in memory SQLite one; any async engine works the same.

import factory
from models import Hero, Team
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel.ext.asyncio.session import AsyncSession

from sqlmodel_async_factory import AsyncSQLModelFactory

engine = create_async_engine("sqlite+aiosqlite:///:memory:")
session = AsyncSession(engine, expire_on_commit=False)


class TeamFactory(AsyncSQLModelFactory):
    class Meta:
        model = Team
        sqlalchemy_session = session
        sqlalchemy_get_or_create = ("name",)

    name = factory.Sequence(lambda n: f"team-{n}")
    headquarters = factory.Faker("city")


class HeroFactory(AsyncSQLModelFactory):
    class Meta:
        model = Hero
        sqlalchemy_session = session

    name = factory.Sequence(lambda n: f"hero-{n}")
    secret_name = factory.LazyAttribute(lambda hero: f"{hero.name} in disguise")
    team = factory.SubFactory(TeamFactory)

TeamFactory reuses a team that already has the same name, and HeroFactory creates a new team for each hero unless one is given.

Create, await, use

import asyncio

from factories import HeroFactory, TeamFactory, engine, session
from sqlmodel import SQLModel


async def main() -> None:
    async with engine.begin() as connection:
        await connection.run_sync(SQLModel.metadata.create_all)

    hero = await HeroFactory.create()
    print(hero.name, hero.secret_name, hero.team.name)

    teammates = await HeroFactory.create_batch(3, team=hero.team)
    print([teammate.team_id for teammate in teammates])

    preventers = await TeamFactory.create(name="Preventers")
    same_team = await TeamFactory.create(name="Preventers")
    print(preventers.id == same_team.id)

    await session.close()
    await engine.dispose()


asyncio.run(main())

It prints:

hero-0 hero-0 in disguise team-0
[1, 1, 1]
True
  • HeroFactory.create() created team-0 first, committed it, then created the hero with it.
  • The three teammates share the team passed explicitly, so no other team was created.
  • The second Preventers team is the first one, found by name.

The same factories in a pytest suite, one fresh database per test: using it with pytest.

Why it exists

It was extracted from the test suite of a production FastAPI application whose database access is async end to end. Every attempt to reuse the stock SQLAlchemy factory ended in a copy of the same glue in each project, so the glue became a package, with the SubFactory case handled once and properly. How it works is described in the design page.

License

This project is licensed under the terms of the MIT license.