Skip to content

Migrations

Schema migrations with sqlx migrate: file layout, CLI workflow, embedding migrations in your binary, and offline CI builds.

sqlx includes a first-party migration runner. Migrations are plain .sql files in a directory; sqlx tracks which ones have been applied and runs them in order. No DSL, no ORM, plain SQL.

Setup

# Cargo.toml
[dependencies]
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "migrate", "postgres"] }
# or for SQLite:
# sqlx = { version = "0.8", features = ["runtime-tokio", "migrate", "sqlite"] }

Install the CLI:

# Postgres only (smaller binary)
cargo install sqlx-cli --no-default-features --features rustls,postgres

# All databases
cargo install sqlx-cli

The CLI needs a DATABASE_URL set in the environment or a .env file:

DATABASE_URL=postgres://user:password@localhost/mydb

Migration files

Naming convention

<VERSION>_<description>.sql

VERSION is any string that parses as a positive i64. The CLI uses Unix timestamps by default; sequential integers (0001, 0002) also work and are easier to read.

Creating files

sqlx migrate add create_users
# → migrations/20240115120000_create_users.sql

sqlx migrate add -r add_posts
# → migrations/20240115120001_add_posts.up.sql
# → migrations/20240115120001_add_posts.down.sql

The -r flag creates a reversible migration with paired .up.sql and .down.sql files. Once you use -r for one migration, all subsequent migrations in that directory must also be reversible.

Directory layout

  • migrations/
    • 20240115120000_create_users.sql
    • 20240115120001_add_posts.up.sql
    • 20240115120001_add_posts.down.sql
    • 20240115120002_add_email_index.up.sql
    • 20240115120002_add_email_index.down.sql
  • src/
    • main.rs
  • Cargo.toml

Writing migrations

A non-reversible migration is a single file:

-- migrations/20240115120000_create_users.sql
CREATE TABLE users (
    id         BIGINT      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email      TEXT        NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

A reversible migration is a pair:

-- migrations/20240115120001_add_posts.up.sql
CREATE TABLE posts (
    id         BIGINT      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id    BIGINT      NOT NULL REFERENCES users (id),
    title      TEXT        NOT NULL,
    body       TEXT        NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- migrations/20240115120001_add_posts.down.sql
DROP TABLE posts;

CLI workflow

# Show applied and pending migrations
sqlx migrate info

# Apply all pending migrations
sqlx migrate run

# Revert the most recently applied migration (reversible only)
sqlx migrate revert

migrate run is safe to call on startup; it’s a no-op if everything is already applied.

Running migrations in code

Embed migrations into the binary at compile time using the migrate! macro. The path is relative to the project root (Cargo.toml):

sqlx::migrate!("./migrations")
    .run(&pool)
    .await?;

Or as a static to share across tests:

use sqlx::migrate::Migrator;

static MIGRATOR: Migrator = sqlx::migrate!("./migrations");

Call it once at startup, before the server begins accepting requests:

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let pool = PgPoolOptions::new()
        .max_connections(10)
        .connect(&std::env::var("DATABASE_URL")?)
        .await?;

    sqlx::migrate!("./migrations").run(&pool).await?;

    // start server...
    Ok(())
}

Triggering recompilation

The migrate! macro embeds files at compile time but Cargo won’t automatically recompile when SQL files change. Add a build.rs to fix this:

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

How sqlx tracks applied migrations

On first run, sqlx creates a _sqlx_migrations table in your database:

CREATE TABLE _sqlx_migrations (
    version        BIGINT  NOT NULL PRIMARY KEY,
    description    TEXT    NOT NULL,
    installed_on   TIMESTAMPTZ NOT NULL DEFAULT now(),
    success        BOOLEAN NOT NULL,
    checksum       BYTEA   NOT NULL,
    execution_time BIGINT  NOT NULL
);

Each applied migration gets a row. migrate run checks this table, compares checksums, and only runs files with versions not yet present.

Offline mode

By default, sqlx verifies query! and query_as! macros against a live database at compile time. In CI, you often don’t have a running database during the build step. cargo sqlx prepare solves this by generating a .sqlx directory of cached metadata:

# Run locally with a database available
cargo sqlx prepare

# Commit .sqlx/ to version control
git add .sqlx

In CI, build with offline mode:

SQLX_OFFLINE=true cargo build

Testing with migrations

Apply migrations against a test database in integration tests using the static Migrator:

use sqlx::PgPool;

static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");

#[sqlx::test(migrator = "MIGRATOR")]
async fn test_create_user(pool: PgPool) -> sqlx::Result<()> {
    let user = sqlx::query!("INSERT INTO users (email) VALUES ($1) RETURNING id", "alice@example.com")
        .fetch_one(&pool)
        .await?;

    assert!(user.id > 0);
    Ok(())
}

#[sqlx::test] creates an isolated database per test, runs your migrations, and drops the database when the test finishes. Tests run in parallel with no shared state.

Type to search…

↑↓ navigate↵ selectEsc close