Generate a re-runnable Prisma seed file
A good seed file gives every developer the same realistic data after a fresh migrate reset. Writing it by hand means repeating PrismaClient setup, looping to create rows, and wrapping everything so a failure does not leave a dangling connection. This builder produces a complete, idempotent seed.ts from a short description of your models.
How it works
For each model you list with its fields, the builder emits an upsert inside a loop. upsert is the key choice: it takes a where (a unique match), an update, and a create, so re-running the seed never duplicates rows or violates a unique constraint. The first field you list becomes the unique match key.
The generated file:
- instantiates a single
const prisma = new PrismaClient(), - defines an
async function main()that loops the requested number of times per model, varying values ([email protected],[email protected], and so on) so each row is distinct, - calls
main()then chains.catch()to log andprocess.exit(1), and.finally()toawait prisma.$disconnect().
Field values are inferred from the field name and a small type hint — strings get readable text, numbers get an index-based integer, booleans alternate, and dates use new Date(). Relation fields are left as a clearly marked TODO because they require real foreign keys.
Tips and notes
- Configure the seed command once: add
"prisma": { "seed": "tsx prisma/seed.ts" }topackage.json. Thennpx prisma db seedandprisma migrate resetboth run it. - The unique match field (first in your list) must be
@idor@uniqueinschema.prisma, or theupsertwill not behave idempotently. - Seed parent models before child models so foreign keys exist when you fill in the relation TODOs.
- Keep the
$disconnect()infinally— leaving the client open can hang the process or exhaust the connection pool in CI.