Database: Seeding
Introduction
dust-framework includes the ability to seed your database with test data using seeder functions, giving you a test account, sample records, and baseline reference data right after running migrations.
A seeder is an async function annotated with #[seeder]. New applications place seeders in database/seeders, and db:seed runs the default database seeder unless you specify another:
// database/seeders/mod.rsuse dust::db::seeder;use dust::model::create;use crate::models::User;/// Seed the application's database.#[seeder(default, without_events)]pub async fn database() -> dust::Result<()> { // User::factory().count(10).create().await?; create!(User::factory() { name: "Test User", email: "test@example.com", }) .await?; Ok(())}To populate your database using your default seeder, execute the db:seed command:
dust db:seedWriting seeders
A seeder takes no parameters and returns dust::Result<()>. Inside a seeder, you may insert records using create!, the query builder, raw SQL, or model factories. The function's name serves as the seeder's CLI name. For example, this seeder creates your application's default roles:
// database/seeders/roles.rsuse dust::db::seeder;use dust::model::row;use crate::models::Role;#[seeder]pub async fn roles() -> dust::Result<()> { let roles = ["admin", "editor", "viewer"].map(|name| row!(Role { name })); Role::upsert(roles, [Role::name], [Role::name]).await?; Ok(())}Because upsert matches roles by name (assuming a unique index on name), re-running this seeder will not insert duplicate rows.
Seeders run inside your application context like console commands, so config(), dust::resolve, and your models are all available:
let importer = dust::resolve::<CatalogImporter>().await?;Where seeders live
New applications mount database/seeders as the seeders module in src/lib.rs:
// src/lib.rs#[path = "../database/seeders/mod.rs"]pub mod seeders;dust-framework discovers every #[seeder] function compiled into your crate automatically, so adding a new seeder only requires declaring its module in database/seeders/mod.rs. Re-export the seeder function as well so other seeders and tests can invoke it:
// database/seeders/mod.rsmod posts;mod roles;pub use posts::posts;pub use roles::roles;Using model factories
Writing out columns for dozens of records by hand quickly becomes tedious. You may use model factories inside seeders to generate realistic test data. For example, this seeder creates ten users with five published posts each:
// database/seeders/posts.rsuse dust::db::seeder;use crate::models::{Post, User};#[seeder]pub async fn posts() -> dust::Result<()> { User::factory() .count(10) .has(User::posts, Post::factory().published().count(5)) .create() .await?; Ok(())}When seeding thousands of rows that you do not need returned as model instances, call insert on the factory instead of create to write rows in bulk statements rather than one insert per record. Bulk inserts skip model events, so a searchable model is not synced; run search:import after the seeder, or sync the rows yourself.
Calling additional seeders
As your seed data grows, split it into focused seeder functions and invoke them in order from your default database seeder:
#[seeder(default, without_events)]pub async fn database() -> dust::Result<()> { roles().await?; posts().await?; comments().await?; Ok(())}Each seeder executes at most once per db:seed run, even when multiple seeders call it. That means a seeder can safely call the seeders it depends on without creating duplicate records. For example, comments calls super::posts() so running db:seed comments on its own still has posts to comment on:
// database/seeders/comments.rsuse dust::db::seeder;use crate::models::{Comment, Post, User};#[seeder]pub async fn comments() -> dust::Result<()> { super::posts().await?; let users = User::all().await?; let posts = Post::all().await?; Comment::factory() .count(300) .recycle(&users) .recycle(&posts) .insert() .await?; Ok(())}If you need a reusable helper that runs multiple times with different arguments, such as creating two teams of different sizes, write a regular async fn instead of a #[seeder] and call it from your seeders.
Muting model events
When seeding development data, you typically do not want model events firing side effects such as welcome emails. Adding without_events to #[seeder(without_events)] mutes model events for that seeder and every seeder it calls, so listeners like Created<User> will not run:
// database/seeders/users.rsuse dust::db::seeder;use crate::models::User;#[seeder(without_events)]pub async fn users() -> dust::Result<()> { User::factory().count(50).create().await?; Ok(())}Model hooks still execute, so fields populated in a creating hook (such as slugs) are still set. The default database seeder enables without_events out of the box.
Seeder patterns
Most seeders are one of a few shapes. Pick the one that matches the job:
| Goal | Pattern | Why |
|---|---|---|
| Baseline reference data, such as roles | upsert by a unique column, or first_or_create |
Safe to run on every deployment |
| Refresh reference data to the current values | update_or_create |
Updates existing rows instead of skipping them |
| A demo or test account with fixed credentials | create! with explicit values |
The values are predictable |
| Realistic sample data | Factories with count and has |
Relationships and required columns stay correct |
| A large fixture | Factory insert with recycle for parents |
Fast, and parents are not duplicated |
| A prerequisite another seeder needs | Call the other seeder | Each seeder runs at most once per db:seed |
| Parameterized setup used twice | A plain async fn |
A #[seeder] runs once and takes no parameters |
| Bulk rows followed by search | insert, then search:import |
Bulk writes skip index syncs |
A seeder is not a migration. Data your application needs before it can serve a request, such as permission definitions, belongs in a migration so it exists on every database in every environment. Seeding is for data you can regenerate or refresh.
Seeders you can run again
Running the default seeder twice fails on the email column's unique index because the test user already exists. During local development, migrate:fresh --seed avoids this by starting from an empty database. For a seeder you intend to run in production, such as one that adds default roles, make it idempotent using first_or_create, update_or_create, or upsert (as in the roles seeder above).
| Approach | Second run | Updates an existing row |
|---|---|---|
create! with fixed values |
Fails on the unique index | No |
User::factory().create() |
Inserts a new user with a new random email | No |
first_or_create |
Returns the existing row | No |
update_or_create |
Returns and updates the existing row | Yes |
upsert |
Updates the columns you list | Yes |
When passing a factory to first_or_create, include the lookup columns in the factory attributes as well:
User::first_or_create( User::email.eq("test@example.com"), create!(User::factory() { name: "Test User", email: "test@example.com" }),).await?;Without overriding email in the factory, each run would generate a random email address and insert a duplicate user.
Required reference data that your application depends on before handling requests belongs in a migration, so it runs once per database during every deployment.
Running seeders
Run db:seed to execute your default seeder, or pass a seeder's name to run only that seeder:
dust db:seeddust db:seed postsdb:seed prints each completed seeder alongside its execution time:
◆ roles 2.1ms
◆ posts 118.0ms
◆ comments 41.6ms
◆ database 163.2ms
◆ Database seeded.dust-framework wraps each db:seed invocation in a single transaction, so if any seeder fails, all changes are rolled back cleanly. On MySQL and MariaDB, statements like TRUNCATE or CREATE TABLE trigger an implicit commit, so rows inserted before them are kept.
If foreign key constraints make insertion order difficult, wrap the operation in without_foreign_key_constraints (on PostgreSQL, this applies only to foreign keys defined with .deferrable()).
Seeding after migrating
To rebuild and seed your development database in one command, pass --seed to migrate:fresh (or --seeder=posts to run a specific seeder). The migrate command accepts the same options:
dust migrate:fresh --seeddust migrate:fresh --seeder=postsChoosing a connection
Seeders run against your default connection unless you specify another with --database. While the command runs, that connection becomes the default so your models and queries target it automatically:
dust db:seed --database=reportingForcing seeders to run in production
Because seeding can modify or overwrite data, db:seed prompts for confirmation in production. Pass --force to run without prompting, such as in a deployment script:
./app db:seed roles --forceTroubleshooting seeding
| Symptom | Cause | Fix |
|---|---|---|
| A unique-constraint error on the second run | The seeder inserts fixed values with create! |
Use first_or_create, update_or_create, or upsert |
| A foreign-key error while inserting related rows | The parent seeder has not run, or the order is wrong | Call the parent seeder first, or wrap the work in without_foreign_key_constraints |
seeder "posts" not found |
The module is not declared in database/seeders/mod.rs |
Declare and re-export it |
| Welcome emails fire during seeding | Events are enabled for that seeder | Add without_events to #[seeder] |
| Rows inserted before a failure are missing | db:seed rolls back on PostgreSQL and SQLite |
Fix the failing seeder and run again |
| Some rows survive a failure on MySQL or MariaDB | TRUNCATE or DDL inside a seeder commits the transaction |
Keep statements that commit out of seeders, or accept the partial run |
| A search page finds nothing after seeding | Bulk inserts skip index syncs | Run search:import, or sync the rows explicitly |
| Seeded data is missing in tests | Seeding is not automatic | Call the seeder in the test setup |
Seeding in tests
To run seeders inside your test suite (for a single test, before every test, or once per test database), check out the testing guide's section on seeding the database.