# Add Cursor Pagination to a GORM API

Yes. An agent adds an after cursor beside limit and offset on the article list and feed, keyed on created_at and id, keeps the response shape, and opens a PR.

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

## What the agent does

The agent reads the list queries before it changes a parameter, because a cursor has to key on the order the query already uses. In a repository laid out like realworld-apps/golang-gin-realworld-example-app, `articles/routers.go` has two list handlers: `ArticleList` reads `tag`, `author`, `favorited`, `limit` and `offset` from the query string and calls `FindManyArticle`; `ArticleFeed` reads `limit` and `offset` and calls `GetArticleFeed` on the signed-in user's `ArticleUserModel`. Both answer `{"articles": …, "articlesCount": n}`, the shape the RealWorld spec fixes. In `articles/models.go`, `FindManyArticle` builds the filtered query twice, once for `Count` and once for the fetch, and orders by `article_models.created_at DESC` with `Offset` and `Limit`; `GetArticleFeed` does the same inside a transaction over the followed authors. `ArticleModel` embeds `gorm.Model`, so it has `ID`, `CreatedAt` and `DeletedAt`. The database is SQLite through `gorm.io/driver/sqlite` with `TranslateError` on, and CI in `.github/workflows/ci.yml` runs `scripts/coverage.sh` on Go 1.21 to 1.23.

The cursor is an addition, not a replacement, because clients written to the spec send `offset`. Both handlers gain an `after` query parameter: an opaque base64 of `created_at` and `id` of the last article the client saw. When `after` is present and `offset` is not, the fetch adds `WHERE (created_at, id) < (?, ?)` in the order the query already uses, `created_at DESC` with `id DESC` appended so two articles created in the same second have a stable order; when `offset` is present, nothing changes. The response keeps `articles` and `articlesCount` and adds `nextCursor`, the encoded key of the last returned article, or absent when the page was short. A malformed cursor is a 422 through the `common.NewError` helper the handlers already use for an invalid param, not a silent first page.

Two things come from reading rather than from a pagination recipe. SQLite does not compare row values `(a, b) < (?, ?)` the way Postgres does in every version the driver supports, so the agent writes the expanded form, `created_at < ? OR (created_at = ? AND id < ?)`, in one helper both queries call, and says so in the description. And `GetArticleFeed` returns a count only when the user follows someone, so the cursor branch keeps that early return and the count semantics unchanged.

In its sandbox the agent runs `go test ./...` first, then adds tests in `articles/unit_test.go` in the pattern of `TestArticleListWithFilters`: it creates 25 articles with the helper that already seeds users and articles, requests `/api/articles?limit=10`, follows `nextCursor` twice, asserts the three pages are disjoint and together are the 25 in `created_at` order, and asserts the last page has no `nextCursor`. A second test sends `offset=10` beside `after` and asserts the offset path wins and the response matches the pre-change behaviour. A third sends a garbage cursor and asserts 422. It runs `scripts/coverage.sh` and `gofmt` as CI does and quotes both.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to the article list and feed in this Gin and GORM API. Read articles/routers.go, articles/models.go, articles/serializers.go, articles/unit_test.go, common/database.go and .github/workflows/ci.yml first. Add an after query parameter to GET /api/articles and GET /api/articles/feed, an opaque base64 of the last article's created_at and id; when it is present and offset is not, page with a created_at and id comparison in the existing DESC order, using the expanded OR form because the database is SQLite. Keep articles and articlesCount unchanged and add nextCursor to the response, absent on the last page. Answer 422 on a malformed cursor. Run go test ./... first, then add tests that three cursor pages over 25 articles are disjoint and complete, that offset beside after keeps the old behaviour, and that a bad cursor is 422. Run scripts/coverage.sh and scripts/gofmt.sh. Open a pull request quoting the results.",
  "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

What comes back is a pull request that changes `articles/routers.go` and `articles/models.go` and adds a small `cursor.go` beside them for encoding and decoding, plus three tests. The two handlers read `after`, the two query functions take an optional cursor and apply the expanded comparison, and the serializer output gains `nextCursor`. `offset` and `limit` behave exactly as before, which the second test pins.

The description quotes `go test ./...` with the three new tests named and the coverage line from `scripts/coverage.sh`, and shows one request chain: `limit=10`, then `after=<cursor>` twice, with the ids each page returned.

Before merging, a reviewer decides whether the comments list in `ArticleCommentList`, which has no pagination at all today, should get the same parameter, and whether to publish `nextCursor` in the API's spec file so the frontend generates a client for it.

## Run it on every Linear issue labelled agent

Pagination problems arrive as bug reports about missing or repeated rows, so a team routes them by label. An automation in the API's Project with the prompt above and a `linear` trigger on `linear.issue.labeled` for the label `agent` starts a run when someone files "the feed shows the same article on page two after someone posts" and labels it. The trigger adds the issue after the prompt, so the run reads which endpoint the issue names and changes that list first.

Each run opens its own pull request on its own branch and links the issue. An endpoint that already has a cursor gets a description saying so and no change; one with a different order gets a cursor keyed on that order, because the run reads the query before it writes the comparison.

## Why run it on Rush?

Offset pagination drifts the moment a row is inserted ahead of the page, and a cursor fixes that only if it keys on exactly the order the query uses and ties are broken. The work is in reading the query, not in the recipe, and the trap here is SQLite's row-value comparison. In a Rush sandbox the agent reads both list functions, writes the comparison the database supports, keeps the spec's offset path untouched, and proves the pages are disjoint and complete before anyone reviews.

The record of the run keeps the test runs and the request chain, and the pull request quotes them, so the reviewer sees three pages adding up to 25 rather than trusting a WHERE clause by eye. Across every Go service a team keeps on GORM, the same request runs in parallel, one sandbox and one pull request each.

## Frequently asked questions

### Why keep offset at all?

Because the RealWorld spec defines limit and offset and the existing frontend sends them. The cursor is additive: a client that sends after gets stable pages, one that sends offset gets exactly what it got before, and a test pins the second case.

### Why is the cursor two fields and not just the id?

The query orders by created_at DESC, and ids are not guaranteed to follow creation time once articles are deleted and recreated or imported. Keying on created_at and id, with id breaking ties, follows the order the client sees. The agent appends id DESC to the ORDER BY so the tie-break is in the query too.

### What is the expanded OR form about?

Postgres compares row values, (created_at, id) < (?, ?), but SQLite's support for that is version-dependent through the driver. created_at < ? OR (created_at = ? AND id < ?) means the same thing everywhere, so one helper builds it for both queries.

### What happens with a bad cursor?

The decode fails and the handler answers 422 with the same common.NewError shape the handlers use for an invalid param, naming the parameter. Silently falling back to the first page would hide a client bug, and a test asserts the 422.

## More GORM jobs

- [Add Database Indexes to GORM Models](https://getrush.ai/run/add-database-indexes/gorm/)
- [Add Database Migrations to a GORM App](https://getrush.ai/run/add-database-migrations/gorm/)
- [Add OpenTelemetry Tracing to GORM Queries in a Go Service](https://getrush.ai/run/add-opentelemetry/gorm/)

## The same job on other stacks

- [Add Cursor Pagination to a Hono API on Workers KV](https://getrush.ai/run/add-cursor-pagination/hono/)
- [Add Cursor Pagination to a Ktor API](https://getrush.ai/run/add-cursor-pagination/ktor/)
- [Add Cursor Pagination to a Litestar API](https://getrush.ai/run/add-cursor-pagination/litestar/)

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