# Wrap Multi-Step Writes in GORM Transactions

Yes. The agent finds each handler that writes more than once, passes one transaction handle through its helpers and tests that a failure rolls it all back.

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

## What the agent does

The agent first lists the request paths that write more than once, since those are the only ones a transaction changes. In a GORM app like realworld-apps/golang-gin-realworld-example-app two of them matter. `ArticleUpdate` in `articles/routers.go` calls `articleModel.Update(updates)` and then `articleModel.ReplaceTags(*newTags)`; when the second call fails the handler answers 422, and the new title and body are already saved. `ArticleCreate` is less obvious. Its validator's `Bind` calls `setTags`, which calls `buildTagModels`, which runs `db.Create` for each tag that does not exist yet. That happens during request binding, before `SaveOne` stores the article, so a create that fails on its article leaves the new tags behind.

Wrapping those handlers in `db.Transaction(func(tx *gorm.DB) error { ... })` is not enough here, and the reason is how the code reaches the database. Every model function fetches the package-level handle with `common.GetDB()`. A helper called inside the closure would still write through that global handle, on a different connection from the pool, outside the transaction. On SQLite, which this repository uses through `gorm.io/driver/sqlite`, the result is worse than a missed rollback: the open transaction holds the write lock, the helper's insert waits for it, and after about five seconds, the driver's default busy timeout, it fails with `database is locked`. On PostgreSQL or MySQL the same code returns no error at all; the helper's write commits by itself and survives the rollback.

So the real change is plumbing. The agent gives `buildTagModels`, `ReplaceTags`, `Update` and `SaveOne` a `*gorm.DB` parameter, passes `tx` inside a transaction and `common.GetDB()` elsewhere, and moves tag creation out of `Bind` so that validating a request never writes. The slug retry loops stay outside the closure: both handlers retry on `gorm.ErrDuplicatedKey`, and each attempt has to be a fresh transaction, because PostgreSQL refuses further statements in a transaction after one has failed. `GetArticleFeed` already opens one with `db.Begin()` around reads and commits it without a rollback path; the agent leaves its behaviour alone and notes it.

Then it proves the rollback. A new test registers a GORM callback, in the test only, that fails the insert of one named tag, sends an update that changes the title and adds that tag, and asserts the 422 together with an unchanged title and no new tag rows. A second test fails the article insert on create and counts `tag_models` before and after. Both fail on the code as it stands, which the agent records before making them pass, and `go test ./...` runs in full afterwards because `articles/unit_test.go` shares one database file across its tests.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Make the multi-step writes in this GORM application atomic. Read go.mod, the database setup, every model function and every handler and validator that calls one first. Run the tests and record the result. List each request path that issues more than one write, including writes that happen during request binding or validation, and for each say what is left behind today when a later step fails. Write a failing test for each path first: inject the failure with a GORM callback registered in the test only, and assert both the error response and that no earlier write persisted. Then wrap each path in db.Transaction and pass the transaction handle explicitly to every helper it calls; no function called inside a transaction may use the package-level database handle. Move any write out of validators. Keep retry loops outside the transaction closure so each attempt is a new transaction. Do not change response bodies or status codes, do not wrap single-statement handlers, and leave read-only transactions as they are but list them. Run the whole suite and the format check. Open a pull request that lists each path with its statements before and after, the functions whose signature changed, and the test output from before and after.",
  "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 whose diff is mostly signatures: the helpers that now take a `*gorm.DB`, their call sites, the two handlers, and the validator that no longer writes. The description has one section per write path with the statements it issues in order, what a failure at each step used to leave in the database, and the test that now pins the rollback.

It also names what was left alone and why. The favorite, unfavorite, follow and comment handlers issue one write of their own, so wrapping them would add a round trip and no safety; the only other write on their path is `GetArticleUserModel`, which creates the caller's `ArticleUserModel` row with `FirstOrCreate` the first time and is harmless to keep when the request fails. The read-only transaction in `GetArticleFeed` is listed with a sentence on its missing rollback. The output of `go test ./...` and `scripts/gofmt.sh` is pasted from before and after, with the new tests shown failing on the old code.

The reviewer's check is a search: after the change, no function reachable from inside a `Transaction` closure should call `common.GetDB()`. The description lists the functions it traced, and a call added on another branch since the run started is the place to look. On SQLite a miss shows up as a five-second stall and a lock error; on other databases it shows up as nothing, which is why the search matters.

## Run it on every write path that must be atomic

This is work a developer hands off in the middle of something else, usually after finding a half-applied update in the data. They send this body to `POST /o/{org}/sessions` from a terminal or an editor's MCP client, with a sentence added that names the endpoint they saw it on, and carry on. Sending a `request_id`, a UUID made once for the job, makes a retried call return the same run instead of starting a second one.

For a larger codebase, send one request per package or per aggregate so each pull request stays reviewable, each with its own `request_id`. Signature changes in shared helpers conflict across branches, so name the shared helpers in the first request and let the later ones build on the merged result.

## Why run it on Rush?

Atomicity is a property you test by making something fail halfway, against a real database, and reading what is left. In its own sandbox the agent runs the repository's suite on its SQLite file, injects the failure, and reads the tables afterwards; the commands and their output are kept in the transcript at `GET /o/{org}/sessions/{id}/messages`. The lock error from a helper on the wrong handle is the kind of finding that only appears when the code is executed.

The change is also wide and mechanical, which makes it a poor fit for an afternoon between meetings and a good one for a run. The developer keeps their branch and their local database as they are, and what returns is a pull request with failing-then-passing tests already attached.

## Frequently asked questions

### Why not just call db.Begin and tx.Commit in the handler?

It works, and it puts the rollback on every early return in your hands. `db.Transaction` commits when the closure returns nil and rolls back when it returns an error or panics, so a new early return cannot leak an open transaction. The agent uses manual control only where a transaction has to span more than one function scope.

### Does this change behaviour for API clients?

Only in the failure case. A request that used to fail halfway and leave a partial write now fails and leaves nothing. Successful requests return the same bodies and status codes, which the existing tests in `articles/unit_test.go` continue to check.

### What about nested transactions?

GORM turns a `Transaction` call made on a transaction handle into a savepoint, so an inner helper that opens its own still joins the outer one. The agent avoids relying on that here: helpers take the handle they are given and do not open transactions themselves, which keeps the boundary visible in the handler.

### Will the tests need a different database?

No. The suite creates its own SQLite file through `common.TestDBInit()` and the new tests use it the same way. If your application runs on PostgreSQL in production, say so in the prompt and the agent installs it in the sandbox from system packages and runs the suite there as well, since lock behaviour differs between the two.

## More GORM jobs

- [Fix "database is locked" Errors in a GORM and SQLite App](https://getrush.ai/run/fix-database-is-locked/gorm/)
- [Add Connection Pooling to a GORM App](https://getrush.ai/run/add-connection-pooling/gorm/)
- [Add Cursor Pagination to a GORM API](https://getrush.ai/run/add-cursor-pagination/gorm/)

## The same job on other stacks

- [Add Transactions to a Mongoose App](https://getrush.ai/run/add-transactions/mongoose/)
- [Add Transactions to a Prisma App](https://getrush.ai/run/add-transactions/prisma/)
- [Add Transactions to a Sequelize App](https://getrush.ai/run/add-transactions/sequelize/)

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