# Add D1 Migrations to a Cloudflare Worker

Yes. An agent moves the CREATE TABLE out of the Worker's request path into a wrangler migration, wires it into dev, deploy and the Vitest setup, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-d1-migrations/cloudflare-workers/). 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 table exists today before it writes a migration. In the `d1-starter-sessions-api-template` of cloudflare/templates, `wrangler.jsonc` binds one database as `DB01` with a `compatibility_date` of `2025-10-08`, and `src/index.ts` creates the schema at request time: `withTablesInitialized` runs the handler, and when the error text contains `no such table: Orders: SQLITE_ERROR` it calls `initTables`, which runs `CREATE TABLE IF NOT EXISTS Orders` with `customerId`, `orderId`, `quantity` and a composite primary key, then retries the handler on a cloned request. A comment above it says this exists to avoid a separate migration step for the demo. `resetTables`, behind `POST /api/reset`, drops and recreates the same table. There is no `migrations/` directory, and `package.json` has `dev` as plain `wrangler dev` with `wrangler` pinned at 4.136.1.

The sibling `d1-template` in the same repository shows the shape the agent copies. It has `migrations/0001_create_comments_table.sql`, a `seedLocalD1` script that runs `wrangler d1 migrations apply DB --local`, a `dev` script that runs that first, and a `predeploy` script that applies the migrations with `--remote` before `wrangler deploy`. The agent writes `migrations/0001_create_orders_table.sql` with the exact statement from `initTables`, changes `dev` to apply migrations to the local database before `wrangler dev`, adds `predeploy` for the remote one, and names the binding `DB01` in both, because the command takes the binding name from the config and not the database name.

Then it removes the request-time path. `fetch` calls `handleRequest` directly, `withTablesInitialized` and `initTables` go, and the error branch that matched on the SQLite message goes with them, so a missing table is now a plain 500 that says the migration was not applied rather than a hidden create. `resetTables` stays, because `POST /api/reset` is part of the demo and the repository's `playwright-tests/d1-starter-sessions-api-template.spec.ts` calls it before creating an order; the agent keeps its statement identical to the migration so a reset cannot leave a different schema from a fresh deploy. The Sessions API code is untouched: `withSession`, the bookmark header and the retry policy in `shouldRetry` do not depend on where the table came from.

The tests need the schema too. `test/index.spec.ts` runs the Worker through `@cloudflare/vitest-pool-workers` 0.21.3 against an isolated D1, which starts empty, and today passes only because the first request creates the table. The agent reads the migrations in `vitest.config.mts` with `readD1Migrations` from `@cloudflare/vitest-pool-workers/config`, hands them to the Worker as a `TEST_MIGRATIONS` binding, and adds a setup file that calls `applyD1Migrations(env.DB01, env.TEST_MIGRATIONS)` from `cloudflare:test` before the tests run, so the spec's `list empty orders` case sees an empty table instead of a missing one. It runs `npm run check` (`tsc && wrangler deploy --dry-run`), `npm test`, and the local `dev` script to show the `d1_migrations` bookkeeping table and `Orders` both present, then the repository-level `pnpm -w check`, which runs the templates linter and would refuse a template whose `package.json` lost its `deploy` or `dev` script.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Move this Worker's D1 schema into wrangler migrations. Read wrangler.jsonc, package.json, src/index.ts, test/index.spec.ts and vitest.config.mts first, and look at how a sibling project with a migrations directory wires its dev and predeploy scripts if one exists in the repository. Write migrations/0001_create_orders_table.sql with the exact CREATE TABLE statement the code runs today. Change the dev script to run wrangler d1 migrations apply DB01 --local before wrangler dev, and add a predeploy script that applies them with --remote. Remove the code that creates the table on a missing-table error so a missing migration fails loudly; keep the reset endpoint, with its statement identical to the migration. Make the Vitest setup apply the migrations to the test database with readD1Migrations and applyD1Migrations before the tests run. Run npm run check, npm test and the dev script, and the repository's check script if there is one, paste the output in the pull request and open it.",
  "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 adds `migrations/0001_create_orders_table.sql` and a test setup file, changes `package.json`, `src/index.ts` and `vitest.config.mts`, and leaves `wrangler.jsonc` and `public/index.html` as they are. The description quotes the `tsc` and dry-run deploy output, the Vitest run with both cases of `test/index.spec.ts` passing against an empty database, and the `wrangler d1 migrations apply` output listing the one migration as applied locally.

A reviewer checks the one thing the tests cannot: that the migration has been applied to the remote database before the new code is deployed, since the old code would have created the table on first use and the new code will not. The `predeploy` script does that for anyone running `npm run deploy`; a deployment that runs `wrangler deploy` some other way needs the `--remote` apply added to it, and the pull request says so.

They also read the diff of `src/index.ts` to confirm nothing else changed in the request path: the session bookmark still comes from the `x-d1-bookmark` header, the write still goes to the primary and the read-after-write still runs in the same session.

## Run it on every Linear issue labelled schema

After the first migration, each schema change is a new numbered file. In the console, add an automation on the Project that holds the repository with a `linear` trigger on `linear.issue.labeled` and the label `schema`, and a prompt that says: add the next wrangler migration for the change the issue describes, update the queries that depend on it, run check and the tests, and open a pull request. The issue is placed after the prompt as the event and fills in nothing, so the column or table comes from whoever wrote the issue. The trigger needs a Linear connection for the automation's runner and fires only when the label is applied by someone in your Rush org.

## Why run it on Rush?

The risk in this job is a schema that exists in three places, the migration, the reset endpoint and the test database, drifting apart, and a deploy that assumes a table the old code used to create on demand. The agent runs the migration, the tests and the dry-run deploy in its own sandbox against the `wrangler` version in your lockfile, so what the pull request claims about each of them was observed, not inferred.

Each of those commands stays in the run's transcript at `GET /o/{org}/sessions/{id}/messages`, with its output, and the changed files are listed with their diff at `GET /o/{org}/p/{project}/sessions/{id}/changes`. When the description says the Vitest cases passed against an empty database with only the migration applied, the run that proved it is there to read.

## Frequently asked questions

### Will the migration run against my production database?

Only when something applies it with `--remote`. The agent adds that as a `predeploy` script so `npm run deploy` applies pending migrations first, and the local `dev` script applies them to the local database only. Wrangler records applied migrations in a `d1_migrations` table, so running the command again applies nothing.

### Does it change the Sessions API code?

No. `withSession`, the `x-d1-bookmark` header and the retry rules in `shouldRetry` stay as they are. The migration creates the table; the request path only stops creating it when a query fails.

### What about the reset endpoint?

It stays, because the repository's Playwright test calls `POST /api/reset` before creating an order. The agent keeps its `DROP TABLE` and `CREATE TABLE` statements identical to the migration and says in the pull request that it is a demo endpoint a real deployment would remove.

### How do the tests get the table?

The Vitest pool for Workers starts each run with an empty D1. The agent reads the migrations in `vitest.config.mts` with `readD1Migrations`, passes them in as a binding and applies them in a setup file with `applyD1Migrations` from `cloudflare:test`, so the tests see the same schema a deploy would.

## More Cloudflare Workers jobs

- [Add a Durable Object to a Cloudflare Worker](https://getrush.ai/run/add-durable-objects/cloudflare-workers/)
- [Set Up GitHub Actions CI and Deploys for a Cloudflare Worker](https://getrush.ai/run/add-github-actions-ci/cloudflare-workers/)
- [Add a Health Check Endpoint to a Cloudflare Worker](https://getrush.ai/run/add-health-checks/cloudflare-workers/)

## More jobs like this: Turn a Linear label into a PR

- [Add Dark Mode to a Reflex App](https://getrush.ai/run/add-dark-mode/reflex/)
- [Add a Dark Mode Toggle to a Vite React App from a Linear Issue](https://getrush.ai/run/add-dark-mode/vite-react/)
- [Add a Dark Theme Setting to a Flutter App from a Linear Issue](https://getrush.ai/run/add-dark-theme/flutter/)

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