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

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrations

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

```toml
# 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:

```bash
# 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:

```bash
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

```bash
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:

```sql
-- 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:

```sql
-- 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()
);
```

```sql
-- migrations/20240115120001_add_posts.down.sql
DROP TABLE posts;
```

:::caution
Never edit a migration that has already been applied. sqlx checksums each file when it runs and
stores the checksum in `_sqlx_migrations`. If the file changes after it's been applied, the next
`migrate run` will fail with a checksum mismatch. Add a new migration instead.
:::

## CLI workflow

```bash
# 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`):

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

Or as a static to share across tests:

```rust
use sqlx::migrate::Migrator;

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

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

```rust
#[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:

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

:::caution
`cargo:rerun-if-changed=migrations` triggers when files are added or removed from the directory,
but content changes to existing `.sql` files may not always trigger a recompile. If you edit a
migration and the compile does not pick up the change, run `touch migrations/` or `cargo clean`.
:::

## How sqlx tracks applied migrations

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

```sql
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:

```bash
# Run locally with a database available
cargo sqlx prepare

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

In CI, build with offline mode:

```bash
SQLX_OFFLINE=true cargo build
```

:::tip
Run `cargo sqlx prepare --check` in CI to catch cases where query macros have
drifted from the cached metadata:

```yaml
# GitHub Actions
- run: cargo sqlx prepare --check
env:
  DATABASE_URL: postgres://postgres:postgres@localhost/test
```

This requires a database in CI for the check step, but not for the build step.

:::

## Testing with migrations

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

```rust
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.

:::note
`#[sqlx::test]` requires the `migrate` feature and a `DATABASE_URL` pointing at a Postgres or
SQLite instance with permission to create and drop databases.
:::

Source: https://codex.mirio.dev/databases/migrations/index.mdx
