# 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 ```bash cargo install sqlx-cli --no-default-features --features rustls,postgres ``` Verify installation: ```bash sqlx --version ``` ## 2) Configure `DATABASE_URL` Set your database connection string: ```bash export DATABASE_URL=postgres://DB_USERNAME:DB_PASSWORD@DB_HOST:DB_PORT/DB_NAME ``` Example: ```bash export DATABASE_URL=postgres://rhythm:rhythm@localhost:5432/rhythm_db ``` ## 3) Create a new migration Create a migration file: ```bash 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): ```bash sqlx migrate add -r create_users ``` ## 4) Run migrations manually Apply pending migrations: ```bash sqlx migrate run ``` Show migration status: ```bash sqlx migrate info ``` Revert the most recent migration (only for reversible migrations): ```bash sqlx migrate revert ``` ## 5) Startup migrations (application) Add this after creating the database pool in `src/main.rs`: ```rust 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.