seedcli: test data that respects your schema
How we built a Go CLI that reads a Postgres or SQLite schema, orders tables by foreign key, and fills them with fake data that passes every constraint.
- Published
- Reading time
- 5 min
- Project
- SeedCLI
- Topics
-
- Go
- Cobra
- pgx
- SQLite
- gofakeit
Every project we start reaches the same afternoon: the schema exists, the screens exist, and there is nothing in the database to look at. Someone writes a seed script. It works until the next migration, then it fails on a foreign key, and from then on nobody trusts it. We built seedcli so that afternoon takes one command. It connects to a PostgreSQL or SQLite database, reads the schema as it is right now, works out which tables depend on which, and inserts fake data that satisfies the keys, uniqueness rules and column types it found. The source is open at github.com/kiridharan/seedcli.
Read the schema, don’t describe it
The obvious design is a config file where you describe each table and what goes in it. We rejected that early. A hand-written description is a second copy of the schema, and second copies drift. seedcli introspects instead: table names, column types, nullability, maximum lengths, primary keys and whether they auto-increment, foreign keys, unique constraints, and on Postgres the allowed values of enum types.
Generation then works in two passes of judgement. Column names come first, because they carry the most meaning: email gets an address, first_name a name, city a city, slug and username something URL-safe, created_at a timestamp. When the name says nothing useful, the type decides, and text respects the column’s maximum length. Enum columns pick from their real allowed values, so a check you added last week is honoured without anyone telling the tool. Nullable columns are left empty about 30% of the time, which is closer to production data than a table where every optional field is filled.
Order matters: Kahn’s algorithm over foreign keys
You cannot insert an order before the customer it belongs to. Foreign keys form a directed graph, and seeding is a topological sort of that graph. We use Kahn’s algorithm because it is easy to reason about and it reports a cycle without extra work.
// Edge from parent to child: the child references the parent.
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
result = append(result, byName[current])
for _, child := range graph[current] {
inDegree[child]--
if inDegree[child] == 0 {
queue = append(queue, child)
}
}
}
if len(result) != len(tables) {
return nil, errors.New("cyclic dependency detected")
}
Tables with no parents go first. Each time a table is done, its children lose one dependency, and any child with none left joins the queue. If the loop ends with tables unvisited, something references itself in a ring. A separate depth-first pass names the tables in the cycle.
Cycles get a best-effort order rather than a hard stop. Self-references are handled separately: an employees.manager_id that points back at employees is left out of the sort entirely, because it is not a dependency between tables. The plan for those is two-phase: insert the rows with the self-reference empty, then update a share of them to point at siblings. Today the first phase is what happens. A nullable self-reference starts empty because the table has no rows to point at yet, and later batches can reference rows from earlier ones.
Keys you can only learn after the insert
Foreign keys need real parent keys, and with auto-incrementing columns you only learn them after the insert. seedcli leaves auto-increment columns out of the insert, records the parent keys it gets back, and hands them to child tables, which pick one at random for each row.
This is where the two databases differ most. Postgres can return the inserted rows from the same statement with RETURNING, so a batch of 100 gives you 100 keys in one trip. SQLite reports the last inserted rowid, which is exact for a single row and needs care for a batch. Capturing keys from multi-row batches is the part of the tool we are still tightening. It is also the honest lesson of building one: inserting is easy, and getting the keys back is where the work is.
Uniqueness and a seed you can repeat
Fake-data libraries repeat themselves sooner than you would expect, and one repeated email fails the whole batch. seedcli keeps a registry of every value it has used per unique column and primary key. On a collision it adds a suffix and tries again, up to 100 times, trimming to the column’s maximum length so the fix does not create a new error.
The --seed flag makes a run reproducible: the same seed against the same schema gives the same data. That matters more than it sounds, because a bug report that says “seed 42, then open the third invoice” can be reproduced by anyone. Reproducibility has a quiet requirement, though. Everything that draws a random number has to run in a stable order. Go randomises map iteration, so a sort that builds its starting queue from a map can visit independent tables in a different order on each run. If you build something like this, sort that queue by name.
What we’d tell a team building something similar
Introspect; do not configure. The schema is already the source of truth, and the tool should read it every time rather than trust a description of it.
Treat the dependency graph as the core of the product. Fake names are the easy part. The order of inserts, the handling of cycles and the capture of keys decide whether the tool works on a real schema or only on a demo.
Make determinism a feature you test, not a flag you add. A seed only helps if the whole run is ordered.
If you’re weighing a build like this for your own team, get in touch.