Skip to main content

seedgraph

Seed your SQLAlchemy models as a referentially-consistent graph — one call, shared parents, verified links.

seedgraph fills your test database with a coherent graph of objects, in a single call. You declare what you want — "3 users, each with 2 posts, each post with 3 comments" — and the library builds the objects, links them, writes them to your session and then verifies every foreign key against the row it points at. Values are realistic and reproducible ("Jose Bishop", not "user-0"), generated by Faker with a fixed seed, valid for each column's type, and unique where the schema says so — even against rows already in the database. You can pin any column, replace how any column is generated, and attach the new graph to rows you already have. It plugs into pytest with no configuration.

Status: pre-alpha. Every guarantee below is backed by a named test, on SQLite and on PostgreSQL.


Why

Every Python team that seeds a relational test database eventually hand-rolls the same plumbing: generate rows, stage commits so primary keys exist, chase those keys into FK columns, repeat for every relationship, and hope the graph stays consistent.

After empirically testing the landscape (SQLAlchemy 2.x era, August 2026), none of the existing options does it:

Tool What you get on a User ← Post ← Comment schema
polyfactory Builds related objects, but every FK column is a random int pointing at nothing: post.author_id != post.author.id. Silent data corruption — tests pass on garbage unless you enable FK enforcement (most don't).
faker-sqlalchemy (unmaintained since 2022, pinned to SQLAlchemy 1.x) RecursionError on standard backref relationships, on self-referential FKs, and its overrides API silently drops FK values.
sqlalchemyseed Seeds data you already have (JSON/YAML), doesn't generate.
sqlseed, sowdb Solid fillers, but schema-level and flat: "N rows per table". They work from raw SQL schemas, not your models, and can't express a graph shape like "3 users → 2 posts each → 5 comments per post".

The one-line failure seedgraph fixes:

p = PostFactory.build()
p.author_id == p.author.id   # False. Every FK in the graph is disconnected.

"But other libraries do this too, don't they?"

They create linked objects. Three differences survive a closer look:

1. A verified exit contract, not just object creation. factory_boy, pytest-factoryboy or mixer build the graph and stop there. seed() flushes the graph, lets the database assign the keys, then walks every link and raises IncoherentGraphError if a foreign key disagrees with the row it points at.

2. Coexistence with a populated database. The database assigns the keys, so seeding on top of existing rows never collides on ids, never desynchronises a PostgreSQL sequence, and stays safe when two sessions seed the same tables at once. Unique columns are checked against the rows already there before anything is written.

3. Determinism wired into pytest. A new session replays the same values from the same seed; consecutive calls on one session continue the sequence instead of repeating it — inside a two-line fixture.

Quick start

Declare a shape from a root model; each key walks a one-to-many or many-to-many relationship, by relationship name or by target class name:

from seedgraph import seed

graph = seed(session, User, post=2, post__comment=3)   # 3 users by default

assert len(graph.users) == 3
assert len(graph.posts) == 6
post = graph.users[0].posts[0]
assert post.author_id == graph.users[0].id          # real key, assigned by the database
assert graph.labels == []                           # any table of the model, empty if not seeded

seed() returns once the graph is flushed and verified; commit or roll back as your test needs. seed_async(async_session, ...) is its twin for an AsyncSession.

Existing and missing parents

alice = session.get(User, 1)
graph = seed(session, Post, parents=[alice])   # every post's author is alice; alice is not in graph.users

graph = seed(session, Comment)   # one Post and one User are generated, shared by all comments

A link first takes the nearest ancestor of its type in the shape, then the object of that type passed in parents (optional links included). A required link still empty gets one generated parent per type, shared by every object that needs it. Several objects of one type are accepted in parents; a link towards a single parent refuses to choose between them with AmbiguousParentError.

Many-to-many

graph = seed(session, Article, article=5, tags=3)            # 15 new tags, 3 per article
graph = seed(session, Article, article=5, parents=[python, sql])   # every article tagged with both existing tags

A count keeps its one-to-many meaning: new objects for each parent. Objects passed in parents join every many-to-many collection of their type, next to the ones the shape builds. SQLAlchemy writes the association rows itself.

Pinning and generating values

graph = seed(
    session,
    User,
    post=2,
    generators={User: {"name": lambda ctx: ctx.fake.first_name()}},   # replace how a column is generated
    overrides={Post: {"title": "Imposed", "subtitle": None}},        # pin a value, None included
)

ctx.fake is the session's seeded Faker; ctx.column is the column name. An override can also be a callable taking the same context.

pytest

Installing seedgraph registers four fixtures, prefixed so they never shadow your own session or graph:

def test_feed(seedgraph_graph):
    graph = seedgraph_graph(User, post=2)       # fresh in-memory SQLite, FK enforced, tables created on demand
    assert len(graph.posts) == 6

async def test_feed_async(seedgraph_agraph):
    graph = await seedgraph_agraph(User, post=2)

seedgraph_session and seedgraph_asession expose the sessions behind them. To seed your own database, call seed() on your own session.

Guarantees and the tests that prove them

Guarantee Test
Every link of the returned graph is verified after flush test_verification.py::test_seed_returns_a_graph_already_written_with_real_keys, ::test_verify_graph_names_the_link_whose_foreign_key_disagrees
Seeding on top of existing rows keeps PostgreSQL sequences intact test_postgres.py::test_the_application_still_inserts_after_a_seed_on_top_of_its_rows
Two sessions seeding the same tables at once do not collide test_postgres.py::test_two_sessions_seeding_the_same_tables_at_once_do_not_collide
Unique columns skip values already in the database test_unique.py::test_a_new_session_on_a_populated_database_skips_the_values_already_taken, ::test_postgres_rows_from_an_earlier_run_do_not_block_a_new_seed
Same seed, same values; consecutive calls do not repeat test_generators.py::test_a_new_session_replays_the_same_values, ::test_two_seeds_in_one_session_continue_the_same_faker_sequence
Generated values fit the column type (enum, length, precision, arrays) test_types.py
Many-to-many shapes build new objects per parent; existing objects are shared test_many_to_many.py::test_a_many_to_many_count_builds_new_objects_for_each_parent, ::test_existing_objects_passed_as_parents_are_shared_by_every_generated_object
Natural and composite primary keys are generated and never collide test_verification.py::test_a_natural_text_key_is_generated, ::test_natural_keys_skip_the_ones_already_in_the_database, ::test_a_composite_integer_key_and_its_composite_foreign_key_are_generated
Multi-column unique constraints hold test_unique.py::test_many_rows_under_one_parent_keep_a_multi_column_constraint, ::test_a_second_session_keeps_a_multi_column_constraint
Existing rows serve as parents; missing required parents are generated once test_parents.py::test_a_parent_already_in_the_database_is_linked_and_left_out_of_the_graph, ::test_a_child_seeded_alone_gets_one_generated_parent_shared_by_all
Plugin fixtures live beside a project's own session and graph test_fixtures.py::test_the_prefixed_fixtures_live_beside_a_project_own_session_and_graph

Limits

  • seed() flushes the session. The keys come from the database; the objects are no longer pending when it returns.
  • A shape key towards a parent is refused, as parents are linked or generated on their own; pass existing ones in parents. View-only relationships are refused too, since nothing would be written.
  • Required columns of uncovered types (JSON, custom TypeDecorator, arrays of those) raise UnsupportedPlaceholderError; declare a generator for them. Nullable ones are left empty.
  • A multi-column unique constraint whose generated columns are only booleans or enums is left to the database. For the others, one generated column is kept unique on its own, which is stricter than the constraint.
  • An association class whose primary key combines its two foreign keys holds one row per parent pair: the generated parent is shared, so two rows under the same parent collide. Seed one per parent, or use a many-to-many relationship.
  • A loop of required links between tables, or a required link to its own table, cannot be generated; pass one side in parents.
  • Determinism holds for a given Faker version. Faker may change its data between releases.

Design principles

  1. Model-first, not schema-first. Works from your SQLAlchemy ORM models and relationships.
  2. Referential consistency is verified, not hoped for. The database assigns the keys, seedgraph checks every link afterwards.
  3. Shared parents are the point. Realistic data shares parents (one author, many posts). One object per FK is not a graph.
  4. Deterministic. A new session with the same calls produces the same graph.
  5. Self-references and mutually referencing tables are normal. Category.parent and tables pointing at each other are supported; only unsatisfiable loops of required links are refused.
  6. Stop generating at the boundary. Existing rows are usable as parents; only missing parents get generated.

Roadmap

  • Shape API (relation=n, nesting, shared parents)
  • Custom field generators (Faker under the hood)
  • Overriding specific attributes on generated objects
  • pytest fixture helpers
  • Self-referential and cyclic FKs
  • Async sessions support
  • Database-assigned keys and post-flush verification, PostgreSQL in the test suite
  • Type-valid values, uniqueness against existing rows, existing and generated parents
  • Many-to-many shapes, generated natural keys, multi-column uniqueness, arrays
  • Publication on PyPI

Installation

pip install seedgraph
pip install "seedgraph[async]"  # for seed_async and the async pytest fixtures

Requires Python 3.11+, SQLAlchemy 2.x and Faker 30+. The async extra adds greenlet (through sqlalchemy[asyncio]) and aiosqlite. The PostgreSQL tests of the suite need Docker and are skipped without it.

License

MIT

Release files for seedgraph 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for seedgraph 0.1.1
File Size Uploaded
seedgraph-0.1.1.tar.gz 85.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for seedgraph 0.1.1
File Interpreter ABI Platform
seedgraph-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 105.6 kB

Release files / seedgraph-0.1.1.tar.gz

Download URL seedgraph-0.1.1.tar.gz
Size 85.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c6b6d492c58679784224d7aee15857c7bacddadf411af242bd6dc1148776f430
BLAKE2b-256 checksum
How to use checksums
53ec6d91074ecfa979d5d0c25107f273059b1b93503963f7c635241374a12c72
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","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}

Release files / seedgraph-0.1.1-py3-none-any.whl

Download URL seedgraph-0.1.1-py3-none-any.whl
Size 20.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f0b109fad9f52b464939d9c1853bd34619324764df5e8222fb6336a2d71a1bce
BLAKE2b-256 checksum
How to use checksums
46dc2ff78f2f594433952a3f28d796c0b2e009c434bad464a9059ff163f7509e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","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}

Release history Release notifications | RSS feed

0.1.2

2 release files

This release

0.1.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page