Migrations
Version database schema with repeatable, ordered migration files - sqlx migrate and refinery are the common Rust choices.
Busca en todas las páginas de la documentación
Version database schema with repeatable, ordered migration files - sqlx migrate and refinery are the common Rust choices.
Quick-reference recipe card - copy-paste ready.
sqlx migrate add create_users
# edit migrations/<timestamp>_create_users.sql
sqlx migrate runsqlx::migrate!("./migrations").run(&pool).await?;When to reach for this: Any service with a persistent database needs auditable schema change history.
-- migrations/20240101000001_create_items.sql
CREATE TABLE items (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);-- migrations/20240102000001_add_items_sku.sql
ALTER TABLE items ADD COLUMN sku TEXT;
CREATE UNIQUE INDEX items_sku_key ON items (sku) WHERE sku IS NOT NULL;#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
sqlx::migrate!("./migrations").run(&pool).await?;
Ok(())
}What this demonstrates:
sku.migrate! on deploy or startup._sqlx_migrations table.| Rule | Why |
|---|---|
| One concern per file | Easier rollback narrative |
| Avoid destructive first deploy | Add column nullable, backfill, then NOT NULL |
| Test on copy of prod data | Catch lock/time issues |
| Run in CI before merge | Catch SQL errors early |
// Diesel migrations (alternative)
// diesel migration runALTER on big tables blocks writes. Fix: Online migration strategies, batch backfills.sqlx migrate run in pipeline against ephemeral DB.| Alternative | Use When | Don't Use When |
|---|---|---|
| Diesel migrations | Diesel ORM stack | sqlx-only services |
| refinery | Library-agnostic SQL files | Already standardized on sqlx CLI |
| Flyway/Liquibase (JVM) | Polyglot org standard | Pure Rust pipeline preferred |
Run in deploy job before traffic; optional sanity check on startup.
Only before first production deploy; never rewrite applied history.
Separate seed scripts, not mixed into schema migrations.
Coordinate migration ownership - one service runs migrations or shared migration repo.
Add nullable -> backfill job -> set NOT NULL in later migration.
Regenerate .sqlx offline data after schema changes affecting query!.
Keep migrations portable or maintain dialect-specific files consciously.
Forward-fix migration preferred over reversing applied files.
Indexes, lock time estimate, backwards compatibility for rolling deploys.
sea-orm-migration generates Rust migration modules - pick one tool per repo.
migrate! macroStack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026