# Add Transactions to a Prisma App

Yes. An agent finds the read-then-write routes in your Prisma and Express app, wraps them in $transaction with isolation and a retry, tests them, and opens a PR.

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

## What the agent does

The agent reads the app before it wraps a query. In an app laid out like the `orm/express` example in prisma/prisma-examples, `package.json` depends on `@prisma/client 7.0.0`, `prisma 7.0.0`, `@prisma/adapter-pg 7.0.0`, `pg 8.20.0` and `express 5.1.0`, with `tsx`, `typescript 5.8.2` and `dotenv` as dev dependencies, one script (`dev: tsx src/index.ts`) and no test runner. `prisma.config.ts` uses `defineConfig` to point at `prisma/schema.prisma`, a `prisma/migrations` directory, a seed command of `tsx prisma/seed.ts`, and a datasource URL read with `env('DATABASE_URL')`. The schema uses the `prisma-client` generator with `output = "./generated"` and two models: `User` (`id`, unique `email`, optional `name`, `posts`) and `Post` (`id`, `createdAt`, `updatedAt`, `title`, optional `content`, `published`, `viewCount`, and an optional `author` relation on `authorId`). `src/index.ts` builds `new PrismaClient({ adapter: new PrismaPg({ connectionString }) })` and mounts the routes: `POST /signup` with a nested `posts.create`, `POST /post` connecting an author by email, `PUT /post/:id/views` with an atomic `increment`, `PUT /publish/:id`, `DELETE /post/:id`, `GET /users`, `GET /user/:id/drafts`, `GET /post/:id` and `GET /feed`. `prisma/seed.ts` runs `post.deleteMany()` then `user.deleteMany()` and creates three users with nested posts.

Most routes are already safe, and the agent says which and why rather than wrapping everything. `/signup`'s nested create is one Prisma write and runs atomically on its own; `/post/:id/views` uses `increment`, which Postgres applies in place. The route that is not safe is `PUT /publish/:id`: it does `findUnique` to read `published`, then `update` with `!postData?.published`, as two statements with no transaction. Two concurrent calls both read `false` and both write `true`, and one toggle is lost. The agent rewrites it as an interactive transaction: `prisma.$transaction(async (tx) => { const post = await tx.post.findUniqueOrThrow(...); return tx.post.update(...) }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable, maxWait: 2000, timeout: 5000 })`, where `tx` is the client every statement must go through. Under `Serializable`, Postgres rejects the second of two overlapping toggles, which surfaces in Prisma as error code `P2034`, so the route retries that code a bounded number of times with a short backoff and answers `409` if it keeps failing. `findUniqueOrThrow` turns the existing silent `{ error: ... }` JSON for a missing post into a `404`.

The second change is a route the app lacks and the schema needs: `DELETE /user/:id`. The `author` relation has no `onDelete` argument, so Prisma's default for an optional relation sets `authorId` to null on the posts of a deleted user, leaving orphan rows. The agent adds the route as a sequential transaction, `prisma.$transaction([prisma.post.deleteMany({ where: { authorId } }), prisma.user.delete({ where: { id } })])`, which runs both statements in one database transaction and rolls both back when the second fails, such as for an id that does not exist. The pull request shows both forms side by side and says when each applies: the array form when the statements do not depend on each other's results, the callback form when a later statement needs an earlier one's value.

There is no test runner, so the agent adds `node --import tsx --test tests/` with the built-in `node:test` module and a `test` script. The tests need a database like the app does: in its sandbox the agent installs Postgres, sets `DATABASE_URL`, runs `npx prisma migrate dev --name init` (the schema has no migrations directory yet) and `npx prisma generate`, then seeds. `tests/publish.test.ts` creates a post, fires twenty `PUT /publish/:id` calls with `Promise.all`, and asserts the final `published` value equals the starting value, since an even number of toggles must cancel out; the agent runs the same test once against the old two-statement route to show it fails under concurrency, and quotes that output in the pull request without committing the old route. `tests/delete-user.test.ts` creates a user with two posts, deletes the user, and asserts both post ids are gone, then deletes a missing user and asserts `404` and that no posts were touched.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add database transactions to this Prisma 7 and Express app. Read package.json, prisma.config.ts, prisma/schema.prisma, prisma/seed.ts, src/index.ts, tsconfig.json and README.md first. Rewrite PUT /publish/:id as an interactive prisma.$transaction with findUniqueOrThrow and update on the transaction client, Serializable isolation, maxWait and timeout set, a bounded retry on Prisma error code P2034, a 409 when retries run out and a 404 for a missing post. Add DELETE /user/:id as a sequential $transaction that deletes the user's posts and then the user, answering 404 when the user does not exist. Leave /signup and /post/:id/views as they are and explain in the pull request why they are already atomic. Add node:test tests run through node --import tsx --test: twenty concurrent publish toggles must leave published at its starting value, and deleting a user must remove its posts. Set up Postgres, run prisma migrate dev, prisma generate and the seed, run the tests, and open a pull request that quotes the 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 changes `src/index.ts` (the rewritten publish route and the new delete-user route) and `package.json` (the `test` script), and adds `tests/publish.test.ts` and `tests/delete-user.test.ts`. `prisma/schema.prisma` does not change, because the fix is in how the writes are grouped rather than in the data model, and the pull request names `onDelete: Cascade` on the `author` relation as the schema-level alternative for teams that want it. Its description quotes the `node --test` output, and quotes the same concurrency test failing against the old route so the lost update is visible as a number rather than a claim.

A reviewer checks the three mistakes interactive transactions invite: a statement inside the callback that used `prisma` instead of `tx` and so ran outside the transaction, a `timeout` long enough to hold a connection from the `pg` pool while a request waits, and a retry that is unbounded. They then decide whether `Serializable` is the level they want on this route, or whether `update` with a `where` that includes the expected `published` value, an optimistic check, would do the same job with no retry loop; the pull request describes that option too.

Every other route serialises the same JSON it did before, and the seed script is unchanged.

## Run it on every pull request that adds a route

An automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` runs on each pull request that touches `src/` and reads the diff for a handler that reads a row and then writes it with two separate `prisma.` calls. An automation's run is read-only, so it posts a review comment that names the file and line and shows the `$transaction` form, rather than pushing to the contributor's branch.

For a first pass over several services, a handler on the reader's own server sends this body once per repository to `POST /o/{org}/sessions`, naming the repository in `resources` and a `request_id` that is a UUID v5 of the repository name, so a retried call returns the run it already started. Each run finds that service's own read-then-write routes, which differ with every schema.

## Why run it on Rush?

A lost update does not show up in a unit test that calls the route once. It shows up when two users click at the same time, and the only way to see it is to make the requests overlap. The agent runs the real server against a real Postgres in its own sandbox, fires the overlapping calls, and keeps the failing count from the old route and the passing count from the new one with the pull request, so the reviewer sees the race rather than reasons about it.

The same audit applies to every Prisma service a team owns, and the routes that need it are different in each. One run per repository, started from a script, gives one pull request per service with a concurrency test written against that service's own models.

## Frequently asked questions

### Sequential or interactive transactions?

Both, each where it fits. `$transaction([a, b])` takes an array of queries and runs them in one transaction, which suits the delete-user route. `$transaction(async (tx) => ...)` gives a transaction client for logic that depends on a read inside the transaction, which the publish toggle needs.

### Why Serializable, and what is P2034?

Under `Serializable`, Postgres refuses to commit the second of two transactions that read and wrote the same row, instead of letting one overwrite the other. Prisma reports that refusal as error code `P2034`, which is the signal to retry. The route retries a bounded number of times and answers `409` after that.

### Why is /signup not wrapped?

A nested write such as `posts: { create: [...] }` inside `user.create` is a single Prisma operation and runs atomically on its own. Wrapping it would add a round trip for nothing, and the pull request says so rather than wrapping every route.

### Does this need Prisma Postgres?

No. The example's README walks through Prisma Postgres, but `prisma.config.ts` reads `DATABASE_URL` from the environment and the `pg` adapter speaks to any PostgreSQL. The agent's tests run against a local Postgres in the sandbox.

### What about the orphan posts the old delete would leave?

The new route deletes them in the same transaction as the user. Adding `onDelete: Cascade` to the `author` relation would move that rule into the database and needs a migration; the pull request describes it as the alternative and leaves the schema unchanged.

## More Prisma jobs

- [Fix updatedAt Columns That Never Update in a Prisma Schema](https://getrush.ai/run/add-updated-at-timestamps/prisma/)
- [Find Slow Postgres Queries in a Prisma App](https://getrush.ai/run/investigate-slow-queries/prisma/)
- [Upgrade a Project to Prisma 7](https://getrush.ai/run/migrate-to-prisma-7/prisma/)

## The same job on other stacks

- [Add Transactions to a Sequelize App](https://getrush.ai/run/add-transactions/sequelize/)
- [Wrap Multi-Step Writes in TypeORM Transactions](https://getrush.ai/run/add-transactions/typeorm/)
- [Wrap Multi-Step Writes in Transactions with Drizzle](https://getrush.ai/run/add-transactions/drizzle/)

## Keep reading

- [What an agent can do in Prisma itself, once you connect it](https://getrush.ai/integrations/prisma/)
- [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/)
