dust

Database: Migrations

Introduction

Migrations are like version control for your database. They let your team define the schema in code and share it. If you've ever had to tell a teammate to add a column to their local database after they pulled your changes, you've faced the problem that migrations solve.

Each migration is a Rust file in database/migrations that changes your schema with the schema builder or with SQL. dust-framework records each migration it runs in a migrations table, so the migrate command runs only the ones that a database hasn't seen. Migrations compile into your application's binary, so a deployed server runs them without your source files.

Generating migrations

You may use the make:migration command to generate a migration. It writes a file in database/migrations whose name starts with the current UTC time, so your migrations run in the order you create them:

shell
dust make:migration create_posts_table

make:migration infers the target table and operation from the migration name. Names such as create_posts_table or create_posts scaffold a new posts table with an id and timestamps, while names such as add_slug_to_posts_table scaffold an alter("posts", ..) block by extracting the table name after the final _to_, _from_, or _in_.

If the table cannot be inferred from the name, the generated migration starts empty. You can also specify the table explicitly with --create=posts for a new table or --table=posts for an existing one.

Naming and order

The timestamp prefix is what orders migrations, and the filename without .rs is the identity dust-framework records in the migrations table. Two consequences follow:

  • Renaming a file changes its identity. A renamed migration that already ran looks missing to migrate:status and new to migrate, so it runs a second time.
  • The prefix decides order, not the order in which migrations were applied. A migration from another branch with an earlier timestamp than one already applied is reported as pending, out of order, and migrate still runs it next.

Keep names descriptive, such as create_posts_table, add_slug_to_posts_table, or drop_legacy_flags_from_users. If two branches create different migrations with the same timestamp, rename the one that has not run yet to a later time before merging; the filenames only need to sort in the order you want.

Migration structure

Each migration defines a single public migrate function that dust-framework executes once per database. For example, this migration creates a posts table using the schema builder, generating the appropriate SQL for PostgreSQL, MySQL, MariaDB, or SQLite automatically:

rust
// database/migrations/2026_10_27_143000_create_posts_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("posts", |table| {            table.id();            table.foreign_id("user_id").constrained().cascade_on_delete();            table.string("title");            table.timestamp("published_at").nullable();            table.timestamps();            table.index(["user_id", "published_at"]);        })        .await}

To see every column type, index, and constraint available on the table blueprint, check out the Schema Builder guide. Migrations may also execute queries with the same query API as the rest of your application, such as running db::query! to backfill a new column. Because migrate runs inside your application context, config() and container services are available as well.

When migrate accepts &mut AnyTransaction<'_>, dust-framework wraps both your migration and its entry in the migrations table inside a single transaction. On PostgreSQL and SQLite, a failed migration rolls back cleanly without leaving partial schema changes behind, so you can fix the file and re-run migrate. Any query executed on the migration's connection automatically participates in the transaction.

MySQL and MariaDB issue an implicit commit whenever a DDL statement such as CREATE TABLE runs, so a failed migration on those engines can leave earlier statements applied. To avoid half-applied migrations on MySQL and MariaDB, keep each table change in its own migration file.

Framework tables

Some of dust-framework's database drivers keep their data in tables you rarely change, such as the database cache store's cache table or the database queue driver's jobs table. Rather than copying each driver's schema into your application, you may create these tables with a migration that holds only the driver's macro:

rust
// database/migrations/0001_01_01_000001_create_cache_table.rsdust::cache::tables!();
Macro Creates
dust::cache::tables!() The cache store's cache and cache_locks tables
dust::feature::table!() The feature flag store's features table
dust::queue::tables!() The queue's jobs, failed_jobs, job_batches, and job_batch_jobs tables
dust::session::table!() The session driver's sessions table
dust::workflow::tables!() The workflow store's five workflow_* tables

Each macro defines the migration's migrate function and runs it in a transaction. If you'd like to change one of these tables later, such as renaming it or adding a column, replace the macro with the migration its guide shows and edit it. A migration that has already run doesn't run again, so make changes to a table that already exists in a new migration.

The migrations a new application ships

An application created with dust new starts with the migrations Laravel's own skeleton ships, plus the relay's table:

Migration Creates
0001_01_01_000000_create_users_table.rs The users and password_reset_tokens tables
0001_01_01_000001_create_sessions_table.rs The sessions table
0001_01_01_000002_create_cache_table.rs The cache and cache_locks tables
0001_01_01_000003_create_jobs_table.rs The jobs, failed_jobs, job_batches, and job_batch_jobs tables
0001_01_01_000004_create_notifications_table.rs The notifications table
0001_01_01_000005_create_relay_stats_table.rs The relay_stats table

The users, notifications, and relay tables are plain migrations, which you may edit. The other three hold the driver macros; to change one of their tables, replace the macro with the migration from that driver's guide and edit it.

Changing a migration that has run

Migrations are forward-only: there is no down function or rollback command. Rolling back a schema change in production is often unsafe because dropping tables or columns risks losing live data, so modifying or undoing a previous migration in a live application is done by writing a new forward migration (such as dropping a column added earlier):

rust
// database/migrations/2026_11_02_090000_drop_posts_published_at.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .alter("posts", |table| {            table.drop_column("published_at");        })        .await}

dust-framework tracks each migration by its filename (without .rs). Once a migration has run in a shared or production environment, never edit or rename it: an edited migration will not run again, and a renamed migration will run a second time.

[!NOTE] During local development before your application has launched (or before a new migration has been deployed), you can modify the table's existing migration directly and run migrate:fresh to rebuild your local database from scratch.

Writing a data migration

A migration can change data as well as schema. The common pattern is to add a nullable column in one migration, fill it in, and only then require it. Suppose an earlier migration added a nullable active column. This migration backfills it in batches, using the primary key so each batch starts after the previous one:

rust
// database/migrations/2026_11_05_090000_backfill_users_active.rsuse dust::db::{self, AnyTransaction};pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    let mut last = 0_i64;    loop {        let ids: Vec<i64> = db::query!(            tx,            "SELECT id FROM users WHERE id > {last} ORDER BY id LIMIT 1000"        )        .select_as::<i64>()        .await?;        let Some(&last_id) = ids.last() else {            break;        };        last = last_id;        db::query!(tx, "UPDATE users SET active = TRUE WHERE id IN ({...ids})")            .update()            .await?;    }    Ok(())}

Because this version accepts &mut AnyTransaction<'_>, the whole backfill runs in one transaction: simple and safe to roll back, but expensive on a large table. For millions of rows, accept &AnyConnection instead so each batch commits, and make the migration idempotent, as Running a migration without a transaction describes.

A column that becomes NOT NULL must have no NULL left. Tighten it in a later migration with .change(), after the backfill has run everywhere.

Running a migration without a transaction

Some statements cannot execute inside a transaction, such as an online concurrent index build on PostgreSQL, and large data backfills often need to commit in batches rather than holding a single long-running transaction. To opt out of the automatic transaction, accept &AnyConnection instead of &mut AnyTransaction<'_>:

rust
// database/migrations/2026_10_27_160000_index_posts_slug.rsuse dust::db::AnyConnection;pub async fn migrate(db: &AnyConnection) -> dust::Result<()> {    // A failed concurrent build leaves an invalid index behind, so drop it before trying again.    db.query("DROP INDEX CONCURRENTLY IF EXISTS posts_slug_index").statement().await?;    db.schema()        .alter("posts", |table| {            table.index("slug").online();        })        .await?;    Ok(())}

Each statement commits immediately, and dust-framework records the migration once migrate returns Ok(()). If a non-transactional migration fails partway through, statements that already ran remain applied and the next migrate run will execute the file from the top, so write these migrations to be idempotent (such as using IF EXISTS above).

Supporting several databases

While most applications target a single database engine, packages often ship migrations that need to run on whichever database an application uses. The schema builder translates portable schema definitions for you, whereas raw SQL is sent as written. When a migration requires engine-specific SQL, branch on tx.driver():

rust
// database/migrations/2026_10_28_090000_index_published_posts.rsuse dust::db::{AnyTransaction, Driver};pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    // MySQL and MariaDB have no partial indexes, so they index every row...    let sql = match tx.driver() {        Driver::Postgres | Driver::Sqlite => {            "CREATE INDEX posts_published_at_index ON posts (published_at) WHERE published_at IS NOT NULL"        }        Driver::MySql | Driver::MariaDb => {            "CREATE INDEX posts_published_at_index ON posts (published_at)"        }    };    tx.query(sql).statement().await?;    Ok(())}

Running migrations

To run every migration that hasn't run yet, use the migrate command:

shell
dust migrate

migrate creates the migrations table the first time, then runs the pending migrations in name order. If a migration fails, migrate stops and prints the database's error with the SQL that caused it. The migrations before it stay applied, so once you fix the failing migration, run migrate again to run the rest.

Creating a missing database

On a new machine, your configuration may point to a database that doesn't exist yet. On PostgreSQL, MySQL, and MariaDB, migrate and migrate:fresh prompt to create it automatically, or pass --force to create it without prompting. The configured database user must have permission to create databases.

SQLite creates the database file itself when the connection URL ends in ?mode=rwc, as the database guide shows.

Checking which migrations have run

migrate:status lists every migration and whether it has run. Each time you run migrate, the migrations it runs share one batch number:

text
Migration                                  Batch  Status
2026_09_01_120000_create_audits_table      1      ran, not registered
2026_10_20_090000_create_teams_table       1      ran
2026_10_21_110000_add_team_to_users               pending, out of order
2026_10_27_143000_create_posts_table       2      ran
2026_10_28_101500_create_comments_table           pending

pending, out of order indicates a pending migration with an earlier timestamp than one that has already run (such as a migration merged from another branch); migrate will still execute it. ran, not registered indicates a migration recorded in the database that is no longer present in your application, usually because its file was renamed or deleted.

After you squash your migrations, the migrations in the schema dump no longer have files. migrate:status leaves them out of the list and counts them on one line below it instead, such as 42 migrations are squashed into the schema dump.

Rebuilding the database

During local development, you may want to rebuild your database from scratch. The migrate:fresh command drops every table and view in the database and then runs all migrations from the beginning:

shell
dust migrate:fresh

migrate:fresh drops all tables in the database, including tables created outside dust-framework migrations, so avoid running it against a database shared with another application. On PostgreSQL, it also drops functions, procedures, custom types (including enums), domains, and sequences in the schemas on your search path while leaving installed extensions (such as citext) and their objects intact.

To seed the database immediately after rebuilding it, pass --seed to run your default seeder, or pass --seeder=posts to run a specific seeder:

shell
dust migrate:fresh --seed

Choosing a connection

Migrations run against your default connection unless you pass --database to migrate, migrate:fresh, or migrate:status. That connection also becomes the default while the command runs, so raw db::query! calls inside migrations automatically target it as well:

shell
dust migrate --database reporting

Running migrations in production

Because migrations can alter or drop production data, migrate and migrate:fresh ask for confirmation whenever APP_ENV is production or unset. Pass --force to run without prompting, such as in a deployment script (on a server, invoke your compiled binary directly rather than dust):

shell
./app migrate --force

When deploying across multiple servers, run migrate from a single server or deployment step. Because migrate does not acquire a distributed lock, running it concurrently from multiple instances can cause two servers to execute the same migration at once.

[!NOTE] When deploying on DUST Cloud, deployment commands automatically run once per deployment, so you do not need to coordinate this yourself.

Registering migrations

New applications register their database/migrations directory in src/app.rs, so every migration you add there runs automatically:

rust
use dust::Application;use dust::foundation::ApplicationBuilder;pub fn configure() -> ApplicationBuilder {    Application::configure()        .with_migrations(dust::db::migrations!("database/migrations"))        // ...}

The migrations! macro reads that directory at compile time and embeds every .rs file directly inside it. Subdirectories are not scanned, so keep all migration files directly inside database/migrations.

Rebuilding after adding a migration

Cargo recompiles automatically when you edit an existing migration, but it does not detect newly added or deleted files on its own. Your application's build.rs instructs Cargo to watch the migrations directory:

rust
// build.rsfn main() {    println!("cargo::rerun-if-changed=database/migrations");}

If you move your migrations to a different directory, update the path in both src/app.rs and build.rs.

Package migrations

Packages can ship their own migrations and register them in their service provider's register method. dust-framework runs package migrations alongside your application's migrations in filename order:

rust
use dust::container::Registrar;fn register(&self, app: &mut Registrar) {    app.migrations().add(dust::db::migrations!("database/migrations"));}

The path is relative to the package's Cargo.toml, and the package needs a build.rs watching database/migrations, as covered in the package development guide.

Squashing migrations

As you build your application, you may accumulate more and more migrations over time. This can lead to your database/migrations directory holding hundreds of migrations, which every new database (including your test databases) has to run. If you'd like, you may "squash" your migrations into a single SQL file. To get started, run the schema:dump command:

shell
dust schema:dump# Dump the current database schema and prune all existing migrations...dust schema:dump --prune

When you run this command, dust-framework writes a schema file to your application's database/schema directory named after the database connection, such as database/schema/postgres-schema.sql. The file contains your database's tables, indexes, and other objects, followed by the recorded rows from your migrations table. Pass --path to write the file to a different location, or --without-migration-data if you only want the schema without the migrations table rows.

Passing --prune deletes the .rs migration files in database/migrations while leaving package migrations untouched.

When you migrate a database with no recorded migrations yet, dust-framework first executes the SQL statements in your connection's schema file and then runs any remaining migrations added since the dump. migrate:fresh does the same after dropping your tables. You may pass --schema-path to load a different file, or --schema-only to load the schema without running pending migrations:

shell
dust migrate:fresh --schema-path=database/schema/archive-schema.sql

New applications embed database/schema into the compiled binary alongside your migrations so a server running only your binary can still build a new database after pruning. Both directories are registered in src/app.rs and watched in build.rs:

rust
// src/app.rspub fn configure() -> ApplicationBuilder {    Application::configure()        .with_migrations(dust::db::migrations!("database/migrations"))        .with_schema(dust::db::schema!("database/schema"))        // ...}// build.rsfn main() {    println!("cargo::rerun-if-changed=database/migrations");    println!("cargo::rerun-if-changed=database/schema");}

If no embedded schema file exists for a connection, dust-framework reads database/schema/<connection>-schema.sql from disk instead.

If your application's tests use a different database connection than local development, dump a schema file for that connection too so your tests can build their database from it:

shell
dust schema:dumpdust schema:dump --database=testing --prune

You should commit your schema files to source control so other developers on your team can quickly create your application's initial database structure.

[!WARNING] Migration squashing supports PostgreSQL, MySQL, MariaDB, and SQLite, and uses the database's command-line client (pg_dump and psql, mysqldump and mysql, or sqlite3). Install the client on any machine that dumps or loads a schema, including CI and production servers. In-memory SQLite test databases load the schema file directly without the client.

Deployment checklist

Migrations change live data, so treat a production run as a deployment step of its own rather than something that happens beside one:

  1. Take a backup or snapshot you can restore, and confirm it finished.
  2. Run migrations from one place. migrate does not take a distributed lock, so two servers running it at once can execute the same file twice.
  3. Use --force in automation. In production, the command prompts for confirmation; a deployment script has no one to answer it.
  4. Prefer additive changes. Add a nullable column or a new table, deploy the code that uses it, then tighten or remove the old shape in a later migration. Dropping a column in the same deploy as the code change leaves no version of the application that works with both.
  5. Keep long work out of the migration transaction. Build indexes concurrently with .online(), batch large backfills, and avoid a single transaction that holds locks for minutes.
  6. Check the result. migrate:status should report every migration as ran and none as pending, out of order.
  7. Remember there is no rollback. If a change was wrong, write a new forward migration that corrects it.
shell
./app migrate:status./app migrate --force

Troubleshooting migrations

Symptom What it means What to do
pending, out of order A pending migration has an earlier timestamp than one already applied, often from a merged branch Run migrate; it executes the pending file
ran, not registered The database recorded a migration whose file is gone, because it was renamed or deleted Restore the filename, or leave the row and add a new migration for further changes
database "app" does not exist The configured database has not been created Let migrate prompt, or pass --force
permission denied to create database The configured user cannot create databases Create it outside the application, or grant the permission
A migration fails halfway on MySQL or MariaDB The DDL statements before the failure committed Fix the failing statement in a new migration; do not edit the failed file in production
no migrations found The directory is not registered, or Cargo did not notice a new file Check with_migrations, build.rs, and the path
A change is missing after migrate The migration was edited after it ran, so it never ran again Write a new migration for the change

When a migration fails, the error includes the SQL that failed. Fix the cause, then run migrate again: on PostgreSQL and SQLite the failed migration rolled back and runs from the top, while on MySQL and MariaDB you must make sure statements that already committed are safe to repeat.

Testing

To run your migrations automatically before each test, call refresh_database when building your test application. dust-framework caches the migrated schema and re-runs migrations whenever a migration file changes. If you've squashed your migrations, dust-framework loads the schema file first, then runs the migrations that came after it.