# Add Transactions to a Sequelize App

Yes. An agent wraps your multi-row Sequelize writes in managed transactions, passes the transaction to every query, proves a failed write rolls back, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-transactions/sequelize/). 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 changes a write. In an app laid out like sequelize/express-example, `express-main-example/package.json` depends on `sequelize ^6.3.3`, `sqlite3 ^5.0.0`, `express ^4.17.1` and `body-parser`, has `start` and `setup-example-db` scripts and no test script, and `.npmrc` sets `package-lock=false`. `sequelize/index.js` opens an SQLite file at `sqlite-example-database/example-db.sqlite` with `logQueryParameters` and `benchmark` on, defines `user`, `instrument` and `orchestra` from `sequelize/models/`, and `extra-setup.js` adds `orchestra.hasMany(instrument)` and `instrument.belongsTo(orchestra)`. `express/app.js` loops over the route modules and mounts `GET`, `POST`, `PUT` and `DELETE` under `/api/<name>` through `makeHandlerAwareOfAsyncErrors`. `express/routes/orchestras.js` creates with `models.orchestra.create(req.body)` and removes with `models.orchestra.destroy({ where: { id } })`; `sqlite-example-database/setup.js` seeds three orchestras and ten instruments each with `orchestra.createInstrument`.

Two routes are not atomic today. A `POST /api/orchestras` whose body carries `instruments` either drops them (no `include`) or, once nested creation is added, inserts the orchestra and then each instrument as separate statements, so an instrument that fails validation (`purchaseDate` is `allowNull: false`) leaves a half-made orchestra behind. `DELETE /api/orchestras/:id` deletes the parent while `hasMany` keeps its default `onDelete: SET NULL`, so the instruments survive with a null `orchestraId`. The agent rewrites both as managed transactions: `sequelize.transaction(async (t) => { ... })`, which commits when the callback resolves and rolls back when it throws, with `{ transaction: t }` passed to the nested `create` (with `include: models.instrument`) and to both `destroy` calls. It does not switch the association to `CASCADE`, because SQLite only enforces foreign keys after `PRAGMA foreign_keys = ON` and the app never sets it; the explicit child delete inside the transaction is the version that behaves the same on every dialect.

To stop `{ transaction: t }` from being forgotten on the next query someone adds, the agent wires CLS: `cls-hooked` becomes a dependency, `sequelize/index.js` creates a namespace and calls `Sequelize.useCLS(namespace)` before the instance is built, so every query inside a `sequelize.transaction` callback joins it without the option. The explicit option stays on the two rewritten routes so a reader sees what is happening, and a short section in `readme.md` explains both forms. Because the example runs on SQLite, which Sequelize drives over a single connection, the agent says in the README that `isolationLevel` is accepted and ignored there, and shows the `Transaction.ISOLATION_LEVELS.SERIALIZABLE` form a Postgres deployment would use.

There is no test runner, so the agent adds one that costs nothing: `node --test tests/` with the built-in `node:test` module, which raises `engines.node` from `>=10` to `>=18` and says so in the pull request. `sequelize/index.js` reads `DB_STORAGE` with the file path as the default, and the tests set it to `:memory:` so they never touch the example database. One test posts an orchestra with two instruments and reads both back under `?includeInstruments`; one posts an orchestra whose second instrument lacks `purchaseDate` and asserts the orchestra count did not change; one deletes a seeded orchestra and asserts `instrument.count({ where: { orchestraId } })` is zero afterwards. The agent runs `npm test` and `npm run setup-example-db` followed by `npm start` against the file database before it opens the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add database transactions to this Sequelize and Express app. Read express-main-example/package.json, index.js, sequelize/index.js, sequelize/extra-setup.js, sequelize/models/*.js, express/app.js, express/helpers.js, express/routes/*.js, sqlite-example-database/setup.js and readme.md first. Rewrite POST /api/orchestras to create the orchestra and its nested instruments inside one managed sequelize.transaction with include, and DELETE /api/orchestras/:id to delete the orchestra and its instruments inside one transaction, passing the transaction to every query. Add cls-hooked with Sequelize.useCLS so queries inside a transaction callback join it automatically, and document both forms in the readme, including that isolationLevel is ignored on SQLite. Make the storage path configurable through DB_STORAGE. Add tests with node:test under tests/ that use :memory: storage and prove a failed nested create rolls back and that deleting an orchestra leaves no instruments behind; add a test script and raise engines.node to >=18. Run npm test, then open a pull request that quotes 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

The pull request changes `express/routes/orchestras.js` (the two transactional routes), `sequelize/index.js` (the CLS namespace and `DB_STORAGE`), `package.json` (`cls-hooked`, the `test` script, `engines`), and `readme.md` (a Transactions section), and adds `tests/orchestras.test.js`. Its description quotes the `node --test` output and shows the SQL Sequelize logs for the rollback case, which is easy to read here because `logQueryParameters` is already on: a `BEGIN`, the inserts, and a `ROLLBACK` with no `COMMIT`.

A reviewer checks the three things that go wrong with transactions in Sequelize: a query inside the callback that was given no transaction and no CLS and so ran outside it, an `await` missing on a nested call so the callback resolves before the write finishes, and an error swallowed by a `try` inside the callback so the transaction commits anyway. The CLS test, which omits `{ transaction: t }` on purpose and still observes the rollback, covers the first. They then decide whether to keep the explicit option on the two routes or rely on CLS alone, and whether the `engines` bump is acceptable for their deployment.

The example database and its seed script are untouched, and `setup.js` keeps its loop of `createInstrument` calls, because seeding does not need atomicity.

## 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 and reads the diff for a route that writes more than one row without a transaction. An automation's run is read-only, so it posts a review comment that names the file and line and shows the managed-transaction form, rather than pushing a fix onto someone else's branch.

For the 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 its own non-atomic writes, which differ from app to app.

## Why run it on Rush?

A transaction bug does not fail a test that only checks the happy path; it leaves a half-written row behind on the one request in a thousand that errors midway. The agent runs the real routes in its own sandbox against a throwaway database, makes the second insert fail on purpose, and keeps the SQL log that shows `ROLLBACK` beside the pull request, so a reviewer sees the failure case handled rather than described.

The same question comes up in every Sequelize service a team owns, and the answer is different in each: which routes write several rows, whether CLS is already wired, which dialect is behind it. One run per repository, started from a script, gives one pull request per service with tests that match its own models.

## Frequently asked questions

### Managed or unmanaged transactions?

Managed: `sequelize.transaction(async (t) => { ... })` commits or rolls back for you. The unmanaged form, `const t = await sequelize.transaction()` with `t.commit()` and `t.rollback()`, is shown in the readme for the case where a transaction has to span more than one function, but the routes use the managed one.

### Why add cls-hooked at all?

Without it, every query inside the callback needs `{ transaction: t }`, and the one that is forgotten runs outside the transaction without any error. `Sequelize.useCLS` makes queries inside the callback join it by default. Sequelize 6 documents this pattern with `cls-hooked`.

### Does the SQLite example behave like Postgres here?

Commit and rollback do. Isolation levels do not: Sequelize runs SQLite over one connection, so `isolationLevel` has no effect there, and the readme says which option a Postgres deployment would set. The tests run on `:memory:` SQLite through `DB_STORAGE`.

### Why not just set onDelete CASCADE on the association?

Because SQLite does not enforce foreign keys until `PRAGMA foreign_keys = ON` is issued on each connection, and the app never sets it, so a cascade would silently not happen there. Deleting the children inside the same transaction works on every dialect, and the pull request notes the cascade as an option for a Postgres-only deployment.

### Will the engines change break anything?

Only running on Node below 18, which the tests need for `node:test`. The application code itself does not use anything new. The pull request calls this out so a team can swap in another runner if they must stay on an older Node.

## More Sequelize jobs

- [Convert a Sequelize Express App to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/sequelize/)
- [Fix "TypeError: sequelize.import is not a function" after upgrading to Sequelize 6](https://getrush.ai/run/fix-sequelize-import-is-not-a-function/sequelize/)
- [Migrate a Sequelize App From SQLite to Postgres](https://getrush.ai/run/migrate-sqlite-to-postgres/sequelize/)

## The same job on other stacks

- [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/)
- [Wrap Multi-Step Writes in GORM Transactions](https://getrush.ai/run/add-transactions/gorm/)

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