Seeding
Introduction
Seeders fill your database with data: reference rows such as roles and countries that every environment needs, or realistic sample records for local development and tests. A seeder is a class with one method, run(), that receives the database connection and inserts whatever it should. A root seeder can call other seeders so you can organise the data by topic and run it all with one command.
pnpm add @plinthjs/databaseWriting a seeder
Extend Seeder and implement run(connection). Use the connection's query builder to insert records.
import { Seeder, sqliteConnection } from '@plinthjs/database'
import type { Connection } from '@plinthjs/database'
class UserSeeder extends Seeder {
async run(connection: Connection): Promise<void> {
await connection.table('users').insert([{ name: 'Ada' }, { name: 'Linus' }])
}
}Inside run() the connection is also available as this.connection, which is convenient in helper methods:
class RoleSeeder extends Seeder {
async run(): Promise<void> {
await this.connection.table('roles').insert({ name: 'admin' })
}
}this.connection only exists while the seeder is being run by the runner. Reading it on a seeder you constructed yourself and have not run throws an error.
Making seeders safe to run twice
A seeder that always inserts will create duplicates when you run it again. Check first, or use an upsert:
class AdminSeeder extends Seeder {
async run(connection: Connection): Promise<void> {
const exists = await connection.table('users').where('email', 'admin@example.com').exists()
if (!exists) {
await connection.table('users').insert({ name: 'Admin', email: 'admin@example.com' })
}
}
}Running seeders
runSeeder(connection, seeder) runs one seeder. It accepts either an instance or the class, in which case it constructs it with no arguments.
import { runSeeder } from '@plinthjs/database'
const db = sqliteConnection()
await db.statement('create table users (id integer primary key autoincrement, name text)')
await runSeeder(db, UserSeeder)
await runSeeder(db, new UserSeeder())
await db.table('users').count() // => 4runSeeders(connection, seeders) runs a list of seeders in order, and Seeder.call(connection, seeders) is the same thing as a static method:
import { runSeeders, Seeder } from '@plinthjs/database'
await runSeeders(db, [UserSeeder, RoleSeeder])
await Seeder.call(db, RoleSeeder)Calling other seeders
A root seeder usually does nothing but delegate. Inside run(), this.call() runs one seeder or a list of them against the same connection:
class DatabaseSeeder extends Seeder {
async run(): Promise<void> {
await this.call([UserSeeder, RoleSeeder])
}
}
await runSeeder(db, DatabaseSeeder)call() accepts classes and instances, and can be nested as deeply as you like.
Running each seeder only once
Calling the same seeder from two places runs it twice. Pass { once: true } to runSeeders() (or Seeder.call()) and each seeder class runs at most once across the whole pass, including the seeders reached through nested this.call() calls.
class ReportSeeder extends Seeder {
async run(): Promise<void> {
await this.call(UserSeeder) // would normally seed users a second time
}
}
await runSeeders(db, [DatabaseSeeder, ReportSeeder], { once: true })
// UserSeeder runs once even though both seeders call itThe default is once: false: every call runs.
Seeding from the command line
In a generated application
A scaffolded app includes a root seeder, src/database/seeders/database-seeder.ts, and a db:seed command. The seeder creates a demo account (test@example.com with the password password) and is written to be safe to run repeatedly. Run it with the console entry at the project root:
npx plinth db:seed
npx plinth db:seed --class=UserSeederWithout --class it runs DatabaseSeeder. With --class=Name it loads src/database/seeders/<name in kebab-case>.ts (for --class=UserSeeder, the file user-seeder.ts) and runs the exported class of that name (or its default export). The command prints a confirmation once the seeder finishes.
To seed straight after rebuilding the schema, add --seed to the refresh command:
npx plinth migrate:refresh --seedGenerate a new seeder with make:seeder, which writes a class stub to src/database/seeders/:
npx plinth make:seeder UserSeederWith the packaged commands
@plinthjs/database ships db:seed and make:seeder next to the migrate commands. Register them with the seedCommands() factory, which returns command classes with the connection already bound (the kernel builds commands with a bare constructor, so a command cannot receive it any other way):
import { createKernel } from '@plinthjs/console'
import { seedCommands, sqliteConnection } from '@plinthjs/database'
const db = sqliteConnection()
const kernel = createKernel(seedCommands(db, { seedersPath: 'src/database/seeders' }))connection may also be a function, () => app.make(DB), which is called when the command runs. databaseCommands(connection, options) registers these two together with every migrate command and make:migration.
db:seed takes --class=Name (default DatabaseSeeder), --path= for the seeders directory (default database/seeders, or the seedersPath option) and --force. It loads <path>/<Name>.ts (or .js), runs the exported class of that name or its default export, and in production it refuses to run without --force. make:seeder Name writes a Seeder stub into the same directory.
A scaffolded app registers its own equivalent commands, which load from src/database/seeders and resolve the connection from the container, so it keeps working without any of this.
Generating data
Seeders are plain code, so build records however you like: loops, helper functions, or a factory. The generated app includes a small helper, makeUser() in src/database/factories/user-factory.ts, that produces a row with sequential values and lets you override any field:
import { makeUser } from '../factories/UserFactory.js'
class UserSeeder extends Seeder {
async run(connection: Connection): Promise<void> {
await connection
.table('users')
.insert([makeUser({ name: 'Ada', email: 'ada@example.com' }), makeUser(), makeUser()])
}
}If you use models, Factories generate model instances for you.
Testing with seeders
Seeders make good fixtures. Create an in-memory connection, run your migrations, then run the seeder:
import { sqliteConnection, Migrator, runSeeder } from '@plinthjs/database'
const db = sqliteConnection()
await new Migrator(db).run(migrations)
await runSeeder(db, DatabaseSeeder)
await db.table('users').where('email', 'test@example.com').exists() // => trueGotchas
runSeeder()does not wrap the seeder in a transaction. If you want all-or-nothing seeding, wrap it yourself withdb.transaction(...)and pass the transaction connection torunSeeder().- Seeders run in the order you give them, so list the ones that other tables depend on (for example roles before users) first.
once: truede-duplicates by seeder class. Two instances of the same class count as the same seeder.