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: a unique value the other session commits meanwhile is regenerated. 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, unique values included | test_postgres.py::test_two_sessions_seeding_the_same_tables_at_once_do_not_collide, ::test_a_unique_value_another_session_commits_mid_seed_is_regenerated |
| 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. It flushes the objects already pending before building the graph, so the unique checks see them; the keys come from the database, and the graph is 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) raiseUnsupportedPlaceholderError; 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 concurrent seed can wait for the other session. When two sessions generate the same unique value, the database holds the second one until the first commits or rolls back; seedgraph then regenerates the value if it was taken. On SQLite the write is not retried, since its drivers open no transaction before a SAVEPOINT: the second session gets the
IntegrityError. - 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
- Model-first, not schema-first. Works from your SQLAlchemy ORM models and relationships.
- Referential consistency is verified, not hoped for. The database assigns the keys, seedgraph checks every link afterwards.
- Shared parents are the point. Realistic data shares parents (one author, many posts). One object per FK is not a graph.
- Deterministic. A new session with the same calls produces the same graph.
- Self-references and mutually referencing tables are normal.
Category.parentand tables pointing at each other are supported; only unsatisfiable loops of required links are refused. - 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.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| seedgraph-0.1.2.tar.gz | 109.7 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| seedgraph-0.1.2-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 131.5 kB
Release files / seedgraph-0.1.2.tar.gz
| Download URL | seedgraph-0.1.2.tar.gz |
|---|---|
| Size | 109.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
515f04f0baf0960723dc75fe9cc7091b9b5851ed9b45dd7180d1770d6ab15252
|
|
BLAKE2b-256 checksum How to use checksums |
69988eb73bc9ac64d989dcb810dc80bc2471c114f7cbc9e835d3d26fb03e8a0b
|
| 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.2-py3-none-any.whl
| Download URL | seedgraph-0.1.2-py3-none-any.whl |
|---|---|
| Size | 21.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d6b4c34f4b6d83d202e6057c58568d1c8ef9826b51b674c89ec77a2fac03d445
|
|
BLAKE2b-256 checksum How to use checksums |
cc81fb83d35bc271c58f03b05f27b7c5123d5b57b745df3531d6a7c62d3cdffb
|
| 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}
|