rhythm-backend/docs/migration.md
Dmitri f79d830cf2
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 6m8s
register
2026-04-17 10:59:29 +02:00

2.0 KiB

SQLx Migration Guide

This project uses SQLx migrations and runs them on application startup.

1) Install SQLx CLI

Prerequisites

  • Rust toolchain installed (rustup)
  • PostgreSQL reachable from your machine
  • DATABASE_URL available

Install command

cargo install sqlx-cli --no-default-features --features rustls,postgres

Verify installation:

sqlx --version

2) Configure DATABASE_URL

Set your database connection string:

export DATABASE_URL=postgres://DB_USERNAME:DB_PASSWORD@DB_HOST:DB_PORT/DB_NAME

Example:

export DATABASE_URL=postgres://rhythm:rhythm@localhost:5432/rhythm_db

3) Create a new migration

Create a migration file:

sqlx migrate add create_users

This generates a timestamped SQL file under migrations/, for example:

  • migrations/20260416103000_create_users.sql

If you want reversible migrations (up/down):

sqlx migrate add -r create_users

4) Run migrations manually

Apply pending migrations:

sqlx migrate run

Show migration status:

sqlx migrate info

Revert the most recent migration (only for reversible migrations):

sqlx migrate revert

5) Startup migrations (application)

Add this after creating the database pool in src/main.rs:

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

Behavior:

  • Pending migrations are applied on every startup.
  • Applied migrations are tracked in the _sqlx_migrations table.
  • If a migration fails, the app fails fast and does not start listening.

6) Team workflow

  • Create a new migration for every schema change.
  • Commit migration files to git.
  • Do not modify migration files that are already applied in shared environments.
  • Add a new migration to evolve schema safely.

7) Production notes

  • Running migrations on startup in production is supported.
  • In multi-instance deployments, one instance may apply migrations while others wait/retry according to orchestration settings.
  • Prefer backward-compatible migrations for rolling deployments.