Embedding migrations with sqlx migrate macro

Learn how the sqlx migrate macro embeds SQL migration files into the binary and runs them at startup so the database schema is created by the app itself

The sqlx::migrate! macro takes the SQL files that describe the database schema and bakes them into the compiled program. When the program starts, it runs any migration the database has not seen yet, in order, and records what it ran. The result is an application that creates its own tables on first run, instead of depending on someone creating them by hand first.

Where This Fits

The last two pages ran queries against a users table that had to exist before the program compiled, and the table got there by a manual step: someone ran the CREATE TABLE statement in a database client. That manual step works for one developer and one database, and it breaks the moment a second developer, a test database, or a fresh server enters the picture, because each one needs the same table and there is no record of who created what. This page replaces the manual step with files that live in the project and run at startup.

Think of it like a recipe card tucked inside a lunchbox. The lunchbox carries its own instructions, so whoever opens it in a new kitchen can make the same meal without phoning home for the recipe. The migration files are the recipe cards, the binary is the lunchbox, and the database is the kitchen.

The Smallest Working Version

The smallest example is one migration file, one static migrator, and three lines in main that run it before the server starts. The migration file lives in a migrations folder at the project root, and its name starts with a version number, then an underscore, then a short description:

migrations/20261114120000_create_users_table.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

The version number is a timestamp in the form year, month, day, hour, minute, second. It orders the migrations: a smaller version runs before a larger one. The description is a human readable name, with underscores between words. The file holds plain SQL, exactly the statement a database client would run.

The project needs the migrate feature added to sqlx. The macros feature is needed too, because migrate! is a macro:

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "migrate", "derive"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Without the migrate feature, the migrate! macro does not exist, and the compiler reports that it cannot find it. The error names the macro, and the fix is the one word in the features list.

The migrator lives in the database module, next to the pool builder:

src/db.rs
use sqlx::{PgPool, migrate::Migrator, postgres::PgPoolOptions};

pub static MIGRATOR: Migrator = sqlx::migrate!();

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}

sqlx::migrate!() with no argument looks for a folder named migrations at the project root, the folder that holds Cargo.toml. It reads every .sql file in that folder at compile time and stores their contents inside the binary. The result is a Migrator, a value that knows the list of migrations and their order. Declaring it as a static means it is built once and shared, like a constant, and any module can use it by importing it from db.

The error type and handlers are the ones from the last two pages. The main function is where the new behavior lands: it builds the pool, runs the migrations, and only then builds the router and serves:

src/main.rs
use axum_project::{
    app,
    db::{MIGRATOR, create_pool},
};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    MIGRATOR
        .run(&pool)
        .await
        .expect("failed to run migrations");
    let router = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

Start with an empty database, one that has no users table at all, and run the server:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_depth cargo run

The server prints its usual startup line, and the table exists by the time it does. Check it from any Postgres client:

SELECT table_name FROM information_schema.tables WHERE table_name = 'users';
 table_name
------------
 users

Create a user to prove the table works, not just that it exists:

curl -X POST http://127.0.0.1:3000/users \
  -H "content-type: application/json" \
  -d '{"name":"Asha","email":"asha@example.com"}'
{"id":1,"name":"Asha","email":"asha@example.com"}

Stop the server and start it again. Nothing changes the second time: the migration is already recorded, so run finds nothing new to do and the server starts exactly as before. Migrations run once per database, not once per start.

Working Setup:

If the server starts against an empty database, the users table appears in information_schema.tables, and the create request returns {"id":1,"name":"Asha","email":"asha@example.com"}, the migration was embedded at compile time and applied at startup. Stopping and starting the server again with no error proves the migration is recorded and not re-applied.

Understanding the Migrator Line by Line

Three lines carry the whole feature, and each one hides a decision worth naming.

The static declaration

pub static MIGRATOR: Migrator = sqlx::migrate!();

A static is a value that lives for the whole run of the program and is built once, before main runs. The migrate! macro expands into an expression that builds a Migrator from the embedded files, so the static holds the full list of migrations from the moment the program starts. Marking it pub lets main import it from the db module. The type Migrator comes from sqlx::migrate, and importing it in db.rs is what makes the annotation compile.

The default folder

sqlx::migrate!()

With no argument, the macro uses ./migrations, relative to the project root. The path is relative to the folder holding Cargo.toml, not relative to the file that calls the macro, which is different from how include_str! resolves paths. That detail matters when the macro is called from a file deep in src: the folder is still the one at the project root. A different folder can be named explicitly, as the variations section shows.

The run call

MIGRATOR
    .run(&pool)
    .await
    .expect("failed to run migrations");

run takes the pool by reference and applies every migration the database has not recorded yet, in version order. It returns a Result, and .expect stops the program with the given message when the result is an error. Stopping is deliberate: a server whose tables are missing or half built cannot answer requests correctly, so starting without the schema would only produce confusing errors later. The run call sits before app(pool) and before the listener binds, so no request can arrive before the schema is ready.

Migrations Must Run Before Serving:

If the run call moves after axum::serve, the server starts accepting requests while the tables may not exist yet, and the first create request fails with a database error about a missing table. The order in main is a requirement, not a convention: pool first, migrations second, router and listener last.

The Concept Behind Embedded Migrations

A migration is a small step in the history of a schema: create a table, add a column, add an index. Each step has a version number, and the database keeps a record of which steps it has already taken. The record lives in a table sqlx creates itself, named _sqlx_migrations, with one row per applied migration. Running the migrator compares the embedded list against that record and applies only the missing steps.

Embedding changes where the steps live. Without embedding, the SQL files sit on disk next to the project, and something outside the program must find them and run them, usually a command line tool run by hand. With embedding, the files are compiled into the binary, so the program carries its own schema history wherever it goes. A fresh server needs no extra setup step and no extra files: the binary and a database address are enough.

cargo build
        |
        v
migrate! reads migrations/*.sql at compile time
        |
        v
SQL is embedded into the binary as a Migrator
        |
        v
Program starts and connects to the database
        |
        v
Migrator reads _sqlx_migrations for applied versions
        |
        v
Pending migrations run in version order
        |
        v
Each applied migration is recorded in _sqlx_migrations
        |
        v
Server starts serving with the schema in place

A beginner should think of _sqlx_migrations as a checklist the database keeps about itself. Each migration is an item on the list, and the database ticks items off as they are applied. The program brings the full list with it, compares it against the ticks, and does only the unticked work.

Why the App Should Own Its Schema

The manual approach has a hidden cost: the schema exists in exactly one place, the database it was created on, and nowhere else. A new developer clones the project, starts the server, and meets errors about a missing table, because nothing in the project says how the table came to be. A test database has the same problem, and a production server has it worst of all, because the person deploying may not be the person who wrote the SQL.

Embedded migrations fix this by making the schema part of the project. The migration files are reviewed like code, committed like code, and deployed with the code. Every database the app connects to ends up with the same schema, because the same binary applies the same migrations in the same order. The history is visible too: reading the migrations folder shows every change the schema has ever been through, in order, with the version numbers as a timeline.

A Richer Complete Example

One migration creates the table. A real project grows the schema over time, so here is a second migration that adds a column, and a look at the record table after both have run.

Create the second file. The version number is later than the first, so it runs after it:

migrations/20261114130000_add_users_nickname.sql
ALTER TABLE users ADD COLUMN nickname TEXT;

The column is nullable, so existing rows get NULL for it and nothing already stored is disturbed. Adding a column with NOT NULL and no default to a table that already has rows would fail, because Postgres would have no value to put in the existing rows. Nullable first, or a default, is the safe shape for a new column on a live table.

The handlers do not change. They select id, name, and email, and the new column is simply not selected, so it never appears in a response. The schema can grow without touching the handlers, which is one of the reasons migrations are separate files instead of code inside the handlers.

Rebuild and run the server. The first migration is already recorded, so only the second one runs. Check the record table:

SELECT version, description FROM _sqlx_migrations ORDER BY version;
     version      |     description
------------------+---------------------
 20261114120000   | create users table
 20261114130000   | add users nickname

The description column holds the file name with underscores turned into spaces. The table also holds the checksum of each file, the time it was installed, and whether it succeeded. The checksum is what stops a quiet edit: changing the contents of a migration that is already recorded makes the next run fail, because the stored checksum no longer matches the file. The rule is strict on purpose. A migration that already ran is history, and history is not rewritten. To change the schema again, write a new migration.

Naming the Folder Explicitly

The default folder is ./migrations. When the project keeps its migrations elsewhere, for example under a db folder, the macro takes the path as an argument:

src/db.rs
pub static MIGRATOR: Migrator = sqlx::migrate!("db/migrations");

The path is still relative to the project root, and the folder must exist at compile time, or the build fails with a message saying the directory was not found. The rest of the code is unchanged: run works the same way regardless of where the files came from. Use the default unless the project has a real reason to move the folder, because the default is what the next reader expects to find.

Generating a Migration File

Writing the timestamp by hand is error prone, so the sqlx command line tool generates the file with the right name. It needs installing once:

cargo install sqlx-cli --version 0.9.0

Then, from the project root:

cargo sqlx migrate add add_users_nickname

The tool creates migrations/20261114130000_add_users_nickname.sql with the current timestamp and an empty body, ready to be filled with SQL. The generated file is the same shape as a hand-written one, and the migrator treats it identically. The tool is a convenience for naming, not a requirement: a file written by hand with the same naming pattern works exactly the same way.

The CLI and the Macro Read the Same Folder:

The command line tool and the migrate! macro both read the migrations folder, but they do different jobs. The tool creates files and can run migrations from the shell. The macro embeds the files into the binary so the program can run them itself. A project can use one, the other, or both, and the folder stays the same either way.

Rebuilding After Adding a Migration

Adding a migration file does not change any Rust source, so cargo build can decide nothing changed and skip the build, leaving the new migration out of the binary. The server then starts, finds no new migration, and the schema stays old. The fix is a build script that tells Cargo to watch the folder:

build.rs
fn main() {
    println!("cargo:rerun-if-changed=migrations");
}

build.rs is a file at the project root that Cargo runs before building. The println! is not ordinary output: the cargo: prefix marks it as an instruction to Cargo, and rerun-if-changed=migrations says to rebuild when anything inside the migrations folder changes. With this file in place, adding a migration triggers a rebuild, and the new file lands in the binary. The sqlx command line tool can generate this file too, with cargo sqlx migrate build-script.

A Missing Rebuild Looks Like a Missing Migration:

When a new migration does not run and there is no error, the usual cause is a stale binary, not a broken migration. The file is on disk, the code compiled fine, and the server started, but the binary was built before the file existed. Check for build.rs first, and rebuild explicitly with cargo build before assuming the migration itself is wrong.

When a Migration Fails

A migration fails when its SQL is wrong for the database it runs against, for example when it creates a table that already exists, or adds a column that is already there. The run call returns an error, the .expect in main stops the program, and the server never starts. The failure is loud and early, which is the point: a half built schema is worse than a stopped server, because the server would answer requests with errors that look like data problems instead of setup problems.

Read the error message before changing anything. It names the migration version and carries the Postgres error, which usually says exactly what went wrong, such as a duplicate table or a missing column. Each migration runs inside a transaction, so a failure partway through rolls the whole migration back and the database stays as it was before that migration started. A migration file that creates a table, inserts a row, and then hits a bad statement leaves no table and no row behind, and no row in _sqlx_migrations. That makes the fix simple: correct the file, rebuild, and run again. Do not write a repair migration for damage that never happened.

What Happens at Startup

The startup sequence with migrations has one more step than the sequence without them, and the step sits between connecting and serving:

main starts
        |
        v
Read DATABASE_URL from the environment
        |
        v
create_pool opens connections to Postgres
        |
        v
MIGRATOR.run applies pending migrations in order
        |
        v
app(pool) builds the Router with the pool as state
        |
        v
TcpListener binds 127.0.0.1:3000
        |
        v
axum::serve accepts requests

The pool is built before the migrations because the migrator needs a connection to run. The router is built after the migrations because the handlers need the tables to exist. Every step depends on the one before it, and reordering any two breaks the chain in a way that fails loudly at startup rather than quietly at the first request.

Testing It

The test for migrations does not test a route. It tests that the migrator creates a usable table. It clears the table, runs the migrator, and then inserts a row, which only succeeds when the table and its columns exist as the migration defines them.

tests/migrations_test.rs
use axum_project::db::{MIGRATOR, create_pool};

#[tokio::test]
async fn migrations_create_a_usable_users_table() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    MIGRATOR.run(&pool).await.expect("migrations failed");
    sqlx::query("TRUNCATE TABLE users RESTART IDENTITY")
        .execute(&pool)
        .await
        .expect("failed to clear users");
    let result = sqlx::query(
        "INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com')",
    )
    .execute(&pool)
    .await
    .expect("insert after migrate failed");
    assert_eq!(result.rows_affected(), 1);
}

Running the migrator twice in the same test would also be a useful check, and it passes silently: the second run finds nothing pending and changes nothing. The test uses the same DATABASE_URL as the server, so it must run against a database whose rows do not matter, because it truncates the table first.

Run the tests with the database running:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_depth cargo test

The migration test should pass:

test migrations_create_a_usable_users_table ... ok

Common Beginner Mistakes

Forgetting the migrate feature

// Wrong - the macro does not exist without the feature
pub static MIGRATOR: Migrator = sqlx::migrate!();
error: cannot find macro `migrate` in crate `sqlx`

The migrate! macro lives behind the migrate feature, and the Migrator type lives behind it too. Without the feature, both names are unknown to the compiler. The fix is one word in Cargo.toml: add "migrate" to the sqlx features list, next to "macros". The two features are separate because a project can use query macros without migrations, and migrations without query macros.

Putting the folder in the wrong place

// Wrong - the macro looks at the project root, not at src
pub static MIGRATOR: Migrator = sqlx::migrate!("src/migrations");

The path in migrate! is relative to the project root, the folder with Cargo.toml. A migrations folder inside src is invisible to the default call, and the build fails saying the directory does not exist. The fix is to move the folder to the project root, or to pass the real relative path. The default call with no argument is the least surprising form, and it only works when the folder sits at the root.

Naming a file without a version number

migrations/create_users_table.sql

A file without a leading number has no version, so the migrator cannot order it and refuses to load it. The build fails with a message about the file name. The fix is the timestamp prefix, 20261114120000_create_users_table.sql, which gives the file a version and a place in the order. The command line tool generates this prefix, which is one more reason to let it create the file.

Editing a migration that already ran

-- Wrong - this file already ran on the dev database, and changing it breaks the checksum
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    nickname TEXT
);

The _sqlx_migrations table recorded the checksum of the original file. Changing the file changes its checksum, and the next run refuses to start at all, failing with failed to run migrations: VersionMismatch(20261114120000), the version number of the edited file. Nothing is applied. The fix is to leave the applied file alone and write a new migration that adds the column, exactly as the richer example does. Applied migrations are history. New changes are new files.

Running migrations after the server starts

// Wrong - requests can arrive before the tables exist
let router = app(pool.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
MIGRATOR.run(&pool).await.expect("failed to run migrations");
axum::serve(listener, router).await.unwrap();

This ordering compiles, because nothing in the types forbids it, and it fails at run time in a way that depends on timing. A request that arrives between the bind and the migration run hits a missing table. The fix is the order shown in the smallest example: pool, migrations, router, listener, serve. The migration step belongs before anything that can serve a request.

Final Complete Example

Here is everything from this page in one project: two migration files, the build script that watches the folder, the database module with the embedded migrator, the router, and the entry point that runs migrations before serving.

migrations/20261114120000_create_users_table.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
migrations/20261114130000_add_users_nickname.sql
ALTER TABLE users ADD COLUMN nickname TEXT;
build.rs
fn main() {
    println!("cargo:rerun-if-changed=migrations");
}
Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "migrate", "derive"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
src/db.rs
use sqlx::{PgPool, migrate::Migrator, postgres::PgPoolOptions};

pub static MIGRATOR: Migrator = sqlx::migrate!();

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/main.rs
use axum_project::{
    app,
    db::{MIGRATOR, create_pool},
};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    MIGRATOR
        .run(&pool)
        .await
        .expect("failed to run migrations");
    let router = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

The app function, handlers, and error type are the ones from the last two pages, unchanged. The only new pieces are the migration files, the migrate feature, the MIGRATOR static, the build.rs, and the three lines in main. That is the whole feature: small in code, large in what it removes, which is the manual step between cloning the project and running it.

Summary

Embedded migrations turn the schema from a manual setup step into a versioned part of the project. The migrate! macro reads the SQL files at compile time and stores them in the binary, the Migrator applies the pending ones in version order at startup, and the _sqlx_migrations table records what ran, with a checksum that forbids rewriting history. The application starts only when the schema is ready, and a fresh database works on first run with no extra commands.

The decision framework is short. When the schema changes, write a new file with a later version number, never edit a file that already ran. When the program starts, run the migrator before serving, and stop the program when a migration fails, because a server without its schema cannot answer honestly. When a new migration seems to do nothing, check the build first, because a stale binary is the usual cause. The schema is now code, and it follows the same rules as code: review it, commit it, and let the program carry it.