# Squash Alembic Migrations into One

Yes. An agent replaces an Alembic chain with one migration generated from the models, proves a fresh database ends identical to the old chain's, and opens a PR.

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

## What the agent does

The agent reads the chain and the models before it touches a file, because a squash is only safe when the single migration produces exactly the schema the old chain produced. In a backend like the one in fastapi/full-stack-fastapi-template, `backend/alembic.ini` points `script_location` at `app/alembic`, and `app/alembic/versions/` holds five revisions: `e2412789c190` creates `user` and `item` with integer ids, `9c0a54914c78` adds maximum lengths to the string columns, `d98dd8ec85a3` replaces every integer id with a UUID through `new_id` columns, a `uuid-ossp` extension and a backfill, `1a31ce608336` adds the cascade on `item.owner_id`, and `fe56fa70289e`, the head, adds a nullable `created_at` to both tables. `env.py` sets `target_metadata = SQLModel.metadata` from `app.models`, reads the URL from `settings.DATABASE_URL` and configures `compare_type=True`. `app/models.py` is the end state: `User` with a `uuid4` default id, a unique indexed `email` of at most 255 characters, `hashed_password`, `created_at` and `items` with `cascade_delete=True`; `Item` with its own UUID id, `title`, `description`, `created_at` and `owner_id` with `ondelete="CASCADE"`. `scripts/prestart.sh` runs `alembic upgrade head` and then `app/initial_data.py`, `init_db` in `app/core/db.py` creates no tables itself, and `.github/workflows/test-backend.yml` runs prestart and `scripts/tests-start.sh` against a Compose `db` with `coverage report --fail-under=90` at the end. `ruff` and `mypy` exclude `alembic` in `pyproject.toml`.

The sandbox has no Docker, so the agent installs Postgres with `apt-get` and starts it, points `DATABASE_URL` at it, and records the baseline: `alembic upgrade head` through the old chain, then `pg_dump --schema-only` into a file. It drops the database, deletes the five files, and generates the replacement with `alembic revision --autogenerate -m "squashed initial schema"` against an empty database, which writes one migration whose `upgrade` creates both tables from the models, with the UUID columns, the length limits, the unique index on `email` and the cascading foreign key, and whose `downgrade` drops them. It reads the generated file line by line: autogenerate names the primary keys and foreign key the way Postgres does by default, so `item_owner_id_fkey` and `user_pkey` match the names the UUID revision created by hand, and the `uuid-ossp` extension, which only the backfill needed, is not recreated.

The revision id is the part that keeps existing databases working. A deployed database holds `fe56fa70289e` in `alembic_version`, so the squashed file keeps that id as its `revision` with `down_revision = None`: a database already at the old head is at the new head without a `stamp`, and a fresh database runs one migration. The agent then proves equivalence rather than asserting it: it upgrades the fresh database with the single migration, dumps its schema the same way, and diffs the two dumps, fixing any constraint or index name that differs until the diff is empty. `alembic check`, which the pinned `alembic>=1.19.1` has, confirms the models and the new head agree, and `bash scripts/prestart.sh` followed by `bash scripts/test.sh` shows the suite passes with the coverage threshold.

Last it writes down what operators must know, because the squash removes history: a database still at a revision older than `fe56fa70289e` cannot upgrade through the new file, so the pull request says to upgrade such a database to the old head from the previous tag before deploying this branch, and notes that the `Dockerfile` copies `alembic.ini` and the `app/` tree, so no deployment path changes.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Squash the Alembic migrations in this backend into a single migration. Read backend/alembic.ini, backend/app/alembic/env.py, every file under backend/app/alembic/versions, backend/app/models.py, backend/app/core/db.py, backend/scripts/prestart.sh, backend/scripts/test.sh and .github/workflows/test-backend.yml first. Install and start Postgres in your sandbox, run the existing chain to head and save a schema-only pg_dump as the baseline. Then delete the old revision files, generate one migration with alembic revision --autogenerate against an empty database, keep the old head's revision id as its revision with no down_revision so deployed databases stay at head, and compare a schema-only dump of a fresh database upgraded with it against the baseline until the diff is empty; fix constraint and index names by hand where they differ. Run alembic check, then the prestart script and the test script. Open a pull request with the diff result, the test output, and a note on what a database older than the previous head must do before deploying.",
  "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

A pull request that deletes four revision files, replaces the fifth with one file of the same revision id whose `upgrade` creates the full schema, and changes nothing outside `app/alembic/versions/`. The description quotes the empty diff between the two schema dumps, the `alembic check` result, and the test run with its coverage figure, and names the one operational rule: a database behind the previous head upgrades there first.

A reviewer checks the generated `upgrade` against `models.py` once, since that file is now the only migration anyone reads, confirms the revision id matches the old head in their production `alembic_version` table, and merges. The next deploy's `prestart.sh` finds the database already at head and runs nothing; a new environment runs one migration instead of five.

## Run it on every terminal hand-off

A developer who has just merged a feature with two more revisions starts this from the terminal with this body and the repository in `resources`, and goes on to the next ticket. The run works from the real chain and the real models, so the single migration is generated from the schema the code expects, not written from memory.

Send a `request_id`, a UUID, with the body so a retried start returns the run it already began. When the turn ends, `GET /o/{org}/sessions/{id}` names the pull request, and a follow-up to the same session can ask to keep the old files under a tag, or to add a `stamp` step to `prestart.sh` for a database that never ran Alembic.

## Why run it on Rush?

A squash is a correctness problem disguised as housekeeping: the only proof that nothing changed is two schema dumps that match, and that needs a database, the old chain, the new file and a diff. The agent runs all of it in its own sandbox and keeps every command and both dumps in the run's record, so the pull request carries evidence rather than the sentence "should be equivalent".

The same run fits any Alembic project: a Django-style app with a data migration that must survive as a separate step, a multi-database setup with one `env.py` per bind, or a service whose first revisions used `op.execute` with raw SQL that autogenerate cannot reproduce. Each gets a squashed file checked against its own baseline, and the pull request says what could not be folded in.

## Frequently asked questions

### What happens to a production database at the old head?

Nothing. The new file carries the old head's revision id, so `alembic_version` already names it and `alembic upgrade head` runs no migration. Only a database behind that revision needs to reach it with the previous release first, which the pull request states.

### Does the single migration recreate the uuid-ossp extension?

No. The old UUID revision created it to backfill `new_id` with `uuid_generate_v4()`; the models generate ids in Python with `uuid4`, so a fresh schema never calls the function. If something else in the project relies on the extension, the run reports it when the schema diff shows a difference, and the pull request adds the `CREATE EXTENSION` back.

### Will autogenerate match the hand-written constraint names?

The old chain created `user_pkey`, `item_pkey` and `item_owner_id_fkey` explicitly, which are the names Postgres gives unnamed constraints anyway. The run does not rely on that: it diffs the two dumps and renames in the migration file until they agree, so the pull request shows the empty diff rather than an assumption.

### Can the squash keep a data migration?

A step that moves data, like the UUID backfill, has no meaning on an empty database and is dropped from the single migration. If a later revision inserted rows the application depends on, the run keeps it as a second file after the squashed one and says why in the pull request.

## More Alembic jobs

- [Write Tests That Run Alembic Migrations Up and Down](https://getrush.ai/run/write-migration-tests/alembic/)
- [Add Database Indexes with an Alembic Migration](https://getrush.ai/run/add-database-indexes/alembic/)
- [Add an Alembic Migration Drift Check to CI](https://getrush.ai/run/add-migration-check-to-ci/alembic/)

## More jobs like this: Hand off a long task

- [Translate a Nuxt App Into Another Language](https://getrush.ai/run/translate-app-strings/nuxt/)
- [Upgrade a React App from React Router 5 to 6](https://getrush.ai/run/upgrade-react-router/react/)
- [Upgrade an Astro Project's DAGs to Airflow 3](https://getrush.ai/run/upgrade-to-airflow-3/airflow/)

## 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/)
