How to Write and Run Migrations with Diesel

Use the Diesel CLI to generate, write, and run SQL migration files that manage your database schema changes.

Diesel migrations are managed via the diesel CLI tool, which generates, runs, and rolls back database schema changes. Install the CLI, generate a migration file, write your SQL, and run it against your database.

cargo install diesel_cli --no-default-features --features sqlite
mkdir -p src/migrations
# Generate a new migration named 'create_users'
diesel migration generate create_users
# Edit the up.sql and down.sql files in the new directory
# Run the migration
diesel migration run

The diesel migration generate command creates a timestamped directory with up.sql (to apply changes) and down.sql (to revert them). You write raw SQL in these files, then diesel migration run executes the up.sql scripts in order, tracking progress in a diesel_schema_migrations table.