Skip to main content

SQLx

Install SQLx

cargo install sqlx-cli

Database Migration

# Create the database
sqlx database create

# Add a migration, replace name
sqlx migrate add -r name

This will create two migration files, one with the pattern timestamp_name.up.sql and one with the name timestamp_name.down.sql - the one is the migration and the second is the revert script.

# Execute migration
sqlx migrate run

Migrate per code

You can embed the migrations into the application, so that the migration will be executed on startup:

let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");

let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url)
        .await
        .expect("Failed to connect to database");

sqlx::migrate!()
        .run(&pool)
        .await
        .expect("Failed to run migrations");