A seeder puts rows in a table. Migrations change the shape of the database;
seeders fill it — reference data a fresh install cannot work without, and
fixtures a developer wants and production must never see.They share the migrations' machinery: the same
QueryInterface, the same "run each one once"
bookkeeping, and the same up/down pair.A seeder file#
up is what running the seeder does; down is what undoing it does. Both get
the QueryInterface and the Prorm instance, so a
seeder can use models instead if that reads better:In TypeScript, createSeeder() is the same object with the types filled in.
Export it as the default export, or export its members by name; the runner
accepts both (before 4.9.2 a default export failed with seeder.up is not a
function):import { createSeeder } from 'ts-prorm-orm';
const seeder = createSeeder({
async up(queryInterface) {
await queryInterface.bulkInsert('roles', [
{ id: 1, name: 'admin' },
{ id: 2, name: 'member' },
]);
},
async down(queryInterface) {
await queryInterface.bulkDelete('roles', { id: { in: [1, 2] } });
},
});
export default seeder; // or: export const { up, down } = seeder;
A .ts seeder needs a runtime that understands TypeScript. Node 22.18+ strips
the types itself; on older Node the runner registers ts-node when it is
installed, and otherwise says to install it or use .js.Running them#
From the CLI — the same connection settings as the
migration commands (DATABASE_URL, or DB_DIALECT and
friends), and ./seeders as the directory:$ npx prorm seeder:create -- --name roles
Created seeders directory: /srv/my-app/seeders
Seeder created: /srv/my-app/seeders/1790460065308-roles.js
seeder:create prefixes the name with Date.now() in milliseconds, not the
YYYYMMDDHHMMSS stamp migrations use, and writes a one-line stub —
module.exports = { up: async (q,s)=>{}, down: async (q,s)=>{} }; — for you to
fill in. Any name works as long as the files sort in the order they should run;
the examples on this page use hand-written timestamps.$ npx prorm db:seed # everything pending
$ npx prorm db:seed -- --name 20260101120000-roles # just one
$ npx prorm db:seed -- --name 20260101120000-roles --force # run it again
$ npx prorm db:seed:status # what has run
$ npx prorm db:seed:undo # undo the last one
$ npx prorm db:seed:undo -- --name 20260101120000-roles
$ npx prorm db:seed:undo:all # undo everything, in reverse
--name takes the file name without its extension. Add --verbose to
db:seed to list what ran after the count.Or in code, which is what the CLI does:import { SeederRunner } from 'ts-prorm-orm';
const runner = new SeederRunner(prorm, { seedersPath: './seeders' });
await runner.runSeeders(); // returns the names it ran
await runner.getSeedStatus(); // [{ name, status, executedAt }]
await runner.undoSeeder(); // the most recent
await runner.undoAllSeeders();
Each seeder runs once. The names of the ones that have run are kept in a
PrormData table, created on demand; seedsTableName renames it. --force
re-runs one, and only in combination with --name, so nothing re-seeds a whole
database by accident.--force re-runs up() as written — it does not undo first. A seeder that
inserts fixed ids will collide with itself on the second run, so either undo it
before forcing, or write an up() that tolerates being run twice.Keeping fixtures out of production#
A seeder with no env field always runs — that is the right default for
reference data. A seeder that declares one runs only in those environments:$ NODE_ENV=production npx prorm db:seed --verbose
Database connection established
Executed 1 seeder(s)
- 20260101120000-roles
$ NODE_ENV=development npx prorm db:seed --verbose
Database connection established
Executed 1 seeder(s)
- 20260101120100-demo-users
The production run skipped demo-users without recording it, so it is still
pending — the development run picks it up and nothing runs twice.The environment comes from --env, else the runner's own env option, else
NODE_ENV. If none of them resolves, an env-scoped seeder is skipped rather
than run — the failure mode that matters is dev fixtures leaking into
production, not reference data arriving late.new SeederRunner(prorm, { seedersPath: './seeders', env: 'development' });
await runner.runSeeders('./seeders', { env: 'test' }); // per call, wins
Seeding with a factory#
Fixture data wants to be plentiful, varied and cheap to write. A factory — a
function that builds one valid row, with overrides — gets you there without a
library: the seeder asks it for as many rows as it needs, and pins down only the
fields a test depends on.import { createSeeder } from 'ts-prorm-orm';
interface UserRow {
email: string;
displayName: string;
createdAt: string;
}
let seq = 0;
function buildUser(overrides: Partial<UserRow> = {}): UserRow {
seq += 1;
return {
email: `user${seq}@example.test`,
displayName: `Test User ${seq}`,
createdAt: new Date(Date.UTC(2026, 0, seq)).toISOString(),
...overrides,
};
}
const seeder = createSeeder({
env: ['development', 'test'],
async up(queryInterface) {
await queryInterface.bulkInsert('users', [
buildUser({ email: 'admin@example.test', displayName: 'Admin' }),
...Array.from({ length: 24 }, () => buildUser()),
]);
},
// Everything the factory makes is on example.test, so down() can remove
// exactly that and nothing a developer added by hand.
async down(queryInterface) {
await queryInterface.bulkDelete('users', { email: { like: '%@example.test' } });
},
});
export const { env, up, down } = seeder;
Deterministic values (a counter, fixed dates) rather than random ones mean two
developers who seed from scratch get the same rows, and a test that fails on one
machine fails on the other. The example.test domain does double duty: it can
never be a real address, and it gives down() a precise predicate.Factories compose. Memberships built from the rows other seeders created look
the ids up rather than assuming them:import { createSeeder } from 'ts-prorm-orm';
const seeder = createSeeder({
env: ['development', 'test'],
async up(queryInterface, prorm) {
const [member] = await prorm.query("SELECT id FROM roles WHERE name = 'member'");
const users: Array<{ id: number }> = await prorm.query(
"SELECT id FROM users WHERE email LIKE '%@example.test' ORDER BY id",
);
await queryInterface.bulkInsert(
'memberships',
users.map((u) => ({ userId: u.id, roleId: member.id })),
);
},
async down(queryInterface, prorm) {
const users: Array<{ id: number }> = await prorm.query(
"SELECT id FROM users WHERE email LIKE '%@example.test'",
);
await queryInterface.bulkDelete('memberships', { userId: { in: users.map((u) => u.id) } });
},
});
export const { env, up, down } = seeder;
seeders/
20260101120000-roles.ts # reference data: no env, runs everywhere
20260101120100-demo-users.ts # env: development, test
20260101120200-demo-memberships.ts # needs both of the above, so sorts after them
Order, and what a seeder should assume#
Files run in filename order, which is why the CLI timestamps them. A seeder that
depends on another's rows must sort after it — but a seeder that needs a
particular id is usually better off looking it up:Two more things worth deciding deliberately:Seeders are not migrations. They assume the tables already exist. Run
migration:run first — the CLI does not chain them for you.
down should be exact. bulkDelete('roles', {}) empties the table,
including rows somebody else added. Delete what the seeder inserted.
What the runner does with each file#
[!WARNING]
Seeders are not wrapped in a transaction. If one throws half-way through its
up(), the rows it already inserted stay, but it is not recorded — so the
next db:seed runs it again from the top and collides with its own rows.
Keep each seeder to one bulkInsert where you can (one statement either lands
or does not), or make up() tolerate a second run.
Resetting a development database#
The full loop from an empty database to a seeded one, and back:Create the schema#
Seeders assume the tables exist; the CLI does not run migrations for you.$ npx prorm migration:run
Database connection established
Running 2 pending migration(s)...
Running migration: 20260926175708-create-users-table
Migration 20260926175708-create-users-table completed
Running migration: 20260926175719-add-users-display-name
Migration 20260926175719-add-users-display-name completed
Executed 2 migration(s)
Seed it#
$ NODE_ENV=development npx prorm db:seed --verbose
Database connection established
Executed 2 seeder(s)
- 20260101120000-roles
- 20260101120100-demo-users
Check the result#
$ npx prorm db:seed:status
Database connection established
Seeder Status:
=============
Executed Seeders:
[UP] 20260101120000-roles
[UP] 20260101120100-demo-users
----------------
Total: 2 (2 executed, 0 pending)
Undo the fixtures, keep the reference data#
db:seed:undo with no name undoes the most recent seeder only:$ npx prorm db:seed:undo
Database connection established
Seeder undone: 20260101120100-demo-users
Start again from nothing#
$ npx prorm db:seed:undo:all
Database connection established
All seeders undone
[!CAUTION]
db:seed:undo:all runs every executed seeder's down(), reference data
included. Against production that deletes the roles your users are attached
to. Nothing in the CLI asks first, so keep it out of production scripts.
Events#
SeederRunner is an EventEmitter, which is enough for progress output or
timing in CI:runner.on('beforeSeed', ({ name }) => console.log(`→ ${name}`));
runner.on('afterSeed', ({ name, duration }) => console.log(`✓ ${name} (${duration}ms)`));
Options#
| Option | Does |
|---|
seedersPath | Where the files are. Defaults to ./seeders; a path passed to runSeeders() wins for that call. |
seedsTableName | Tracking table. Defaults to PrormData. |
pattern | Which files count as seeders. |
env | Environment for scoping, falling back to NODE_ENV. |
runSeeders(path?, options?) additionally takes only (one seeder by name),
env (wins over the runner's) and force (re-run an executed one; needs
only).CLI — the db:seed* commands in full Modified at 2026-10-04 00:40:16