# Add Database Migrations to an Actix Web App

Yes. An agent replaces a hand-run schema.sql with versioned migrations that run at startup on your tokio-postgres pool, proves them on Postgres, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-database-migrations/actix/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the schema reaches the database today. In a service shaped like actix/examples' databases/postgres, Cargo.toml depends on actix-web from the workspace, deadpool-postgres 0.14 with its serde feature, tokio-postgres 0.7, tokio-pg-mapper, confik 0.15 and dotenvor, on the workspace's Rust 2024 edition and 1.98 minimum. src/main.rs loads a `.env`, builds `ExampleConfig` from `EnvSource`, creates the pool with `config.pg.create_pool(None, NoTls)`, and serves `POST` and `GET /users` from a `ThinData<Pool>`. src/db.rs runs sql/get_users.sql and sql/add_user.sql through `include_str!`, substituting `$table_fields` from the `User` mapper. The schema itself is sql/schema.sql: `DROP SCHEMA IF EXISTS testing CASCADE`, `CREATE SCHEMA testing`, and a `testing.users` table with a `BIGSERIAL` id, four text columns and a unique username. README.md step 3 says to run it with `psql -f sql/schema.sql testing_db` and that the step can be repeated because it clears the database, which is exactly the property a migration system exists to remove.

It reads the rest of the workspace for the convention before choosing a tool. basics/todo already uses sqlx with a migrations/ directory of timestamped `.up.sql` and `.down.sql` files, and .github/workflows/ci.yml installs sqlx-cli and runs `sqlx migrate run --source=./basics/todo/migrations` before `cargo check --workspace --bins --examples --tests` and `cargo test --workspace --all-features`. This service, though, is built on tokio-postgres and deadpool, not sqlx, and switching drivers to get migrations would be a rewrite. refinery is the migration crate written for exactly this driver: its `tokio-postgres` feature runs embedded SQL migrations through a `tokio_postgres::Client`, records what it applied in its own history table, and skips anything already applied on the next start.

The change is a migrations/ directory, one dependency and a few lines in main.rs. migrations/V1__create_users.sql carries the schema and table from schema.sql with `CREATE SCHEMA IF NOT EXISTS testing` in place of the drop, so running it twice is safe and running it on a database with data destroys nothing. Cargo.toml adds refinery with the `tokio-postgres` feature. main.rs calls `refinery::embed_migrations!("migrations")` and, after the pool is created and before `HttpServer::new`, takes one client from the pool and runs the embedded migrations against it, failing startup with the migration's name in the error if one cannot apply. sql/schema.sql is removed and README.md's step 3 becomes a sentence saying the app migrates itself on start; step 4's grants stay, because the migration runs as the app's own user, which `createdb -O test_user` already makes the owner.

Then it proves the whole path. In the sandbox the agent starts a Postgres container, creates the user and database the README describes, writes the `.env` with `SERVER_ADDR`, `PG__USER`, `PG__HOST` and the rest, runs `cargo run`, and watches the first start apply V1 and the second start apply nothing. It sends the README's `curl -d '{"email": ...}'` to `POST /users`, reads it back from `GET /users`, and sends the same username twice to confirm the unique constraint still answers as before. It adds an integration test under tests/ that connects with the `PG__` variables when they are set and skips with a message when they are not, so `cargo test --workspace` in CI, which starts no Postgres for this crate, stays green. It finishes with `cargo check --workspace --bins --examples --tests`, `cargo clippy --workspace --all-targets --all-features` and `cargo fmt --check`, which the justfile and ci.yml run.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add database migrations to this Actix Web service. Read Cargo.toml and the workspace Cargo.toml, src/main.rs, src/db.rs, src/config.rs, src/models.rs, every file under sql/, README.md, .env if present, the justfile and the CI workflows first, and note which database driver the service uses, how the schema is applied today, and whether any other crate in the workspace already has a migration convention. Choose a migration crate that works with the service's existing driver rather than switching drivers, and explain the choice. Move the schema into a versioned migration that is safe to run twice and never drops existing data, embed the migrations, and run them at startup after the pool is created and before the server binds, failing startup with a clear error if one cannot apply. Remove the hand-run schema file and update the README. Start Postgres in the sandbox, run the service twice to show the migration applies once, exercise the users endpoints with the README's requests including the duplicate username case, and add an integration test that uses the PG environment variables when set and skips when they are not, so the workspace test job stays green. Run cargo check, cargo clippy and cargo fmt --check as the repository does, and open a pull request that explains the crate choice and quotes the two startups and the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that adds migrations/V1__create_users.sql and tests/migrations.rs, changes Cargo.toml, Cargo.lock and src/main.rs, deletes sql/schema.sql, and rewrites the database setup section of README.md. sql/add_user.sql and sql/get_users.sql are untouched because the table they query is the same.

The description says why refinery was chosen over sqlx for a tokio-postgres service, then quotes the two `cargo run` startups from the sandbox, the first applying V1 and the second finding nothing to apply, the responses to the README's `POST` and `GET /users` requests and the error on the duplicate username, and the output of `cargo test` with the integration test running against the sandbox Postgres. It also shows `cargo clippy` and `cargo fmt --check` passing.

Before merging, a reviewer checks that the migration never drops the schema, decides whether startup should fail or only warn when the history table shows a migration the binary does not know, and plans the first deploy against the existing database, where V1's `IF NOT EXISTS` makes the table creation a no-op and refinery records it as applied. Adding a V2 that puts an index on `email` is a follow-up on the same session.

## Run it on every service still on a hand-run schema

This is a change to start from the terminal and pick up later: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`, then the laptop closes. The run reads the service, writes the migration, runs it twice against a real Postgres and opens the pull request without anyone watching. The sandbox parks with its disk when the turn ends, so a follow-up such as `add a V2 that indexes email` wakes it with the target directory, the container and the branch intact.

A team with several Rust services sends the same body once per repository, one run each, and each run reads that service's own driver and schema file. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so the pull request links collect in one channel. Send a `request_id` so a retried POST returns the run it already started.

## Why run it on Rush?

A migration system is only proven by two starts against a real database: the first must apply, the second must not, and the data written between them must survive. That needs Postgres, the service's own config, and the time to run it, which is why a hand-run schema.sql with a cascade drop lives on. The agent does the two starts in its own sandbox and the pull request carries both logs, so the reviewer reads evidence rather than a description of what the crate should do.

The record also shows the choice being made: the transcript has the agent finding sqlx in basics/todo, checking that this service uses tokio-postgres, and choosing a crate that fits the existing driver instead of rewriting the data layer. A reviewer who would rather fail fast on an unknown migration in the history table says so in a follow-up and the parked sandbox changes one call.

## Frequently asked questions

### Why refinery and not sqlx migrations like the todo example?

Because this service queries through tokio-postgres and deadpool, and sqlx's migrator needs an sqlx pool. refinery runs embedded SQL migrations through the tokio_postgres client the service already has, so the data layer stays as it is and only startup gains a step.

### What happens on the first deploy against a database that already has the table?

V1 uses CREATE SCHEMA IF NOT EXISTS and CREATE TABLE IF NOT EXISTS, so it changes nothing, and refinery records it as applied in its history table. The old schema.sql's cascade drop is gone, so no deploy can clear the data again.

### Does CI need a Postgres service now?

Not for the build. The integration test reads the PG environment variables and skips with a message when they are absent, so cargo test --workspace stays green on the existing runner; the pull request shows the test running for real in the sandbox, and adding a Postgres service to the workflow is a one-block follow-up.

### Can I still run the schema by hand?

The migration file is plain SQL, so psql -f migrations/V1__create_users.sql works, but then refinery has no record of it and will try V1 on the next start, where the IF NOT EXISTS clauses make it a no-op. The README now points at starting the service instead.

### What if a migration fails at startup?

The service exits before binding, with refinery's error naming the migration and the SQL error from Postgres. A migration is applied inside its own transaction, so a failed V2 leaves V1 in place and the history table unchanged.

## More Actix Web jobs

- [Add Graceful Shutdown to an Actix Web App](https://getrush.ai/run/add-graceful-shutdown/actix/)
- [Add Health Checks to an Actix Web Server](https://getrush.ai/run/add-health-checks/actix/)
- [Add Input Validation to an Actix Web App from a Linear Issue](https://getrush.ai/run/add-input-validation/actix/)

## The same job on other stacks

- [Add Alembic Migrations to an aiohttp App](https://getrush.ai/run/add-database-migrations/aiohttp/)
- [Add Database Migrations to a CodeIgniter 4 App](https://getrush.ai/run/add-database-migrations/codeigniter/)
- [Add Database Migrations to a Drizzle App](https://getrush.ai/run/add-database-migrations/drizzle/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
