# Add TypeORM Migrations to a Koa API

Yes. An agent turns off TypeORM synchronize in your Koa API, generates the first migration from your entities, wires it into start and build, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-database-migrations/koa/). 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 before it adds a migration tool. In an API laid out like javieraviles/node-typescript-koa-rest, `src/server.ts` builds a `ConnectionOptions` object with `type: "postgres"`, `url: config.databaseUrl` and `synchronize: true`, then calls `createConnection` and only starts Koa once the connection is up. `src/config.ts` points `dbEntitiesPath` at `src/entity/**/*.ts` when `NODE_ENV` is `development` and at `dist/entity/**/*.js` otherwise, and defaults `databaseUrl` to `postgres://user:pass@localhost:5432/apidb`, the same credentials `docker-compose.yml` gives its `postgres:10-alpine` service. There is one entity, `src/entity/user.ts`, with `id`, a `name` column of length 80 and an `email` column of length 100; the controller in `src/controller/user.ts` refuses a duplicate e-mail with a `findOne` check, so uniqueness lives in application code and not in a constraint. `package.json` pins `typeorm` 0.2.32, `pg` 8.5, `ts-node` 9 and TypeScript 4.2, and no `migration` directory, `ormconfig` file or migration script exists, although the README shows an `ormconfig.json` with a `migrations` glob as something a reader could add.

With `synchronize: true`, every boot diffs the entities against the live database and alters tables in place, which is why a renamed column on this project would drop and recreate it, data included. The agent replaces that with versioned migrations that TypeORM 0.2 already supports. It writes an `ormconfig.ts` at the repository root that reuses `config.databaseUrl` and `config.dbEntitiesPath`, adds `migrations` and a `cli.migrationsDir` that follow the same `NODE_ENV` rule as the entities (`src/migration/*.ts` in development, `dist/migration/*.js` in production), and sets `synchronize: false` with `migrationsRun: true`, so the server applies pending migrations once at startup instead of guessing at schema changes. `src/server.ts` switches from its inline options to that shared configuration, so the CLI and the running app can never disagree about where the entities are.

To generate the first migration the agent needs a database, so it installs PostgreSQL in its sandbox with `apt-get`, creates the `apidb` database and the `user` role from the compose file, and runs `typeorm migration:generate -n InitialSchema` through `ts-node ./node_modules/typeorm/cli.js` against an empty schema. It reads the generated file before keeping it: one `CREATE TABLE "user"` with a serial `id`, `name character varying(80)` and `email character varying(100)`, and a matching `DROP TABLE` in `down`. It adds `migration:generate`, `migration:run` and `migration:revert` scripts to `package.json`, and because `tsconfig.json` compiles everything under `src/`, the migration lands in `dist/migration/` when `npm run build` runs, which is what the `node:14-alpine` Dockerfile executes before `npm run start`.

The agent does not add a unique index on `email` in this pull request, because existing rows could already violate it; instead the description shows the one-line `migration:generate` that would produce that second migration and leaves the decision to the team. It runs `npm run build` (lint plus `tsc`), `npm test` (the Jest suite mocks `typeorm` entirely, so it needs no database), starts the server with `NODE_ENV=development` against the sandbox database to show the `migrations` table and the applied row, and runs `migration:generate` a second time to show it reports no schema difference.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add TypeORM migrations to this Koa API and open a pull request. Read package.json, tsconfig.json, src/server.ts, src/config.ts, every file under src/entity/, the tests under tests/, Dockerfile, docker-compose.yml, .example.env, .github/workflows/ci.yml and the ORM section of README.md first. Create a shared ormconfig that reuses the existing databaseUrl and entity paths, add migrations and a cli.migrationsDir that follow the same NODE_ENV rule as the entities, set synchronize to false and migrationsRun to true, and make src/server.ts use that configuration. Install PostgreSQL in your sandbox, create the database and role from docker-compose.yml, generate the first migration from the current entities with the TypeORM 0.2 CLI, read the generated SQL, and add migration:generate, migration:run and migration:revert scripts. Do not add new constraints; say in the pull request which ones the code implies. Run npm run build and npm test, start the server against the sandbox database to show the migration applied, generate again to show the schema is in sync, and open a pull request with that 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

The pull request adds `ormconfig.ts`, `src/migration/<timestamp>-InitialSchema.ts` and three scripts in `package.json`, and changes `src/server.ts` to load the shared configuration with `synchronize` off. Its description pastes the generated `up` and `down` SQL, the `migrations` table after the first start, the second `migration:generate` saying nothing changed, and the build and test output.

From then on a schema change is a file in `src/migration/` that a reviewer reads, not an `ALTER` the ORM decides at boot. The Heroku deploy in `ci.yml`, which builds the image and releases it, picks up migrations because `migrationsRun` applies them when the dyno starts; the description also shows how to run `migration:run` as a release step instead, for a team that prefers migrations to finish before the new code serves traffic.

Before merging, a reviewer checks that the production `DATABASE_URL` has the right privileges to create the `migrations` table, decides whether `migrationsRun` or an explicit release command fits their deploy, and chooses whether to generate the `email` unique index as the next migration once duplicate rows have been cleaned.

## Run it on every service still running on synchronize

A team with several TypeORM services started from the same boilerplate sends this body once per repository to `POST /o/{org}/sessions`, each with its own repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own entities and generates its own first migration, and the key's `webhook_url` receives one `run.completed` per repository with the pull request link in `result`.

Once migrations are in, the recurring job is the next one. An automation with a `linear` trigger on the label `schema` starts a run for each issue that asks for a column or table, with this prompt adapted to generate a new migration rather than the first; the trigger appends the issue's title and description after the prompt, and an automation run has its own `max_runs_per_hour` cap.

## Why run it on Rush?

Moving off `synchronize` is a one-time change that is easy to get subtly wrong: the CLI reads one config while the app reads another, the compiled `dist/` path differs from the `src/` path, or the first generated migration includes a drop of a table the ORM thought was stale. The agent does it against a real PostgreSQL in its own sandbox, reads the SQL it produced, and proves the app boots with migrations on and the schema reports in sync.

Everything it ran stays with the run: the install of PostgreSQL, the generate command, the server start, the build and the tests, each with its output, so the reviewer reads a diff and a transcript rather than trusting a description. Several services can get the same treatment at once, each in its own sandbox with its own database.

## Frequently asked questions

### Will the first migration touch my existing data?

No. It is generated against an empty database and only creates the `user` table. On a database that already has that table from `synchronize`, the agent's pull request shows how to record the migration as applied without running it, so production does not try to create a table that exists.

### Why TypeORM 0.2's CLI rather than a DataSource file?

Because the project pins `typeorm` 0.2.32, where the CLI reads an `ormconfig` file and `createConnection` is the API in use. Moving to 0.3 and `DataSource` is a separate upgrade with its own breaking changes, and the pull request says so rather than mixing the two.

### Does it add the unique e-mail constraint?

Not in this pull request. The controller checks for duplicates in code, so an index is the right next step, but it would fail on any existing duplicate rows. The description shows the command that generates that second migration once the data is clean.

### What about the Jest tests?

They keep passing unchanged. The suite mocks the `typeorm` module in both test files, so no migration runs during `npm test`; the real check is the server start against the sandbox database, whose output is in the pull request.

## More Koa jobs

- [Add Dependabot to a Koa API](https://getrush.ai/run/add-dependabot/koa/)
- [Add Graceful Shutdown to a Koa API](https://getrush.ai/run/add-graceful-shutdown/koa/)
- [Add Health Check Endpoints to a Koa API](https://getrush.ai/run/add-health-checks/koa/)

## The same job on other stacks

- [Add Database Migrations to a Mongoose App](https://getrush.ai/run/add-database-migrations/mongoose/)
- [Move a Sequelize App From sync() to Migrations](https://getrush.ai/run/add-database-migrations/sequelize/)
- [Add Database Migrations to a Slim 4 App](https://getrush.ai/run/add-database-migrations/slim/)

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