# Migrate an Echo App From GORM v1 to GORM v2

Yes. An agent moves your Echo app from jinzhu/gorm to gorm.io/gorm: driver, struct tags, not-found checks, counts and associations, with the handler tests passing.

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

## What the agent does

The agent starts from `go.mod`. In an app laid out like xesina/golang-echo-realworld-example-app, the module targets Go 1.18 and depends on `github.com/jinzhu/gorm` v1.9.8, `github.com/labstack/echo/v4` v4.1.16, `gopkg.in/go-playground/validator.v9`, `github.com/swaggo/echo-swagger` and `github.com/dgrijalva/jwt-go`, with `github.com/mattn/go-sqlite3` pulled in indirectly by the v1 sqlite dialect. `db/db.go` opens the database with `gorm.Open("sqlite3", "./realworld.db")`, sets `db.DB().SetMaxIdleConns(3)` and `db.LogMode(true)`, opens a second file at `./../realworld_test.db` for tests, and runs `AutoMigrate` for `User`, `Follow`, `Article`, `Comment` and `Tag`. A grep for the v1-only calls (`IsRecordNotFoundError`, `LogMode`, `.DB()`, `Association(...).Error`, `Model(x).Update(x)`, the `unique_index`, `primary_key`, `foreignkey`, `association_autocreate` and `sql:` tags) lands in `db/`, `model/`, `store/` and the handler test, with most of the hits in `store/article.go`.

The dependency change is the easy part: `gorm.io/gorm` plus `gorm.io/driver/sqlite` replace `jinzhu/gorm`, and because the sqlite driver's own `go.mod` asks for Go 1.21 the agent raises the module's `go` directive to match, then runs `go mod tidy`. That has two knock-on edits it makes in the same pull request: `.github/workflows/go.yml` pins `actions/setup-go@v3` to `go-version: 1.18`, and the `Dockerfile` builds on `golang:1.12.1`; both move to a version that can compile the module, and the Dockerfile's cgo and alpine `lib64` arrangement stays as it is, since `mattn/go-sqlite3` still needs cgo.

Then the call sites. `db.New` becomes `gorm.Open(sqlite.Open("./realworld.db"), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})`, and `db.DB()` now returns `(*sql.DB, error)`, so the idle-connection setting and the `d.Close()` in the test `tearDown` go through that handle. Every `gorm.IsRecordNotFoundError(err)` becomes `errors.Is(err, gorm.ErrRecordNotFound)`. The struct tags in `model/user.go` and `model/article.go` move to the v2 spellings (`uniqueIndex`, `primaryKey`, `foreignKey:FollowingID`, and `gorm:"type:int;not null"` in place of the `sql:` tag on `Follow`). `Count(&count)` takes an `int64` in v2, so the store methods that return `int` convert at the boundary rather than change the handler signatures. `us.db.Model(u).Update(u)` becomes `Updates(u)`, which like the v1 struct form skips zero values, and the agent says so in the pull request because a `Bio` cleared to an empty string still does not persist. `Association("Tags").Append(t)` returns an error directly instead of a chain with `.Error`, and the `association_autocreate:false` tag on `Article.Tags` is replaced by `Omit("Tags")` on the create, with tags attached afterwards as before.

The list queries need the most thought. `ListByTag` and `ListByWhoFavorited` chain `Offset`, `Limit` and `Order` before `Association("Articles").Find` and read a separate `Association(...).Count()`; the agent rewrites them as joins through the `article_tags` and `favorites` join tables with the same `Offset`, `Limit` and `Order("articles.created_at desc")`, and a `Count` on the same query, so the paging semantics the handler tests assert stay the same. While there it notices that `ListFeed` counts the user's own articles rather than the feed, keeps that behaviour and lists it as a pre-existing bug for a separate change. It runs `go build ./...`, `go vet ./...` and `go test -v -race ./...` (the `Makefile`'s `test` target), where `handler/handler_test.go` migrates the sqlite test file, loads fixtures through the stores and drives the Echo router, and opens the pull request when they pass.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Migrate this Echo app from github.com/jinzhu/gorm to gorm.io/gorm. Read go.mod, db/db.go, model/*.go, store/*.go, handler/handler.go, handler/handler_test.go, Makefile, Dockerfile and .github/workflows/go.yml first. Replace jinzhu/gorm with gorm.io/gorm and gorm.io/driver/sqlite, raise the go directive to what the driver needs, run go mod tidy, and update the Go version in the workflow and the Dockerfile build stage to match. Convert gorm.Open and the logger, the DB() handle and Close, IsRecordNotFoundError to errors.Is with gorm.ErrRecordNotFound, the struct tags to v2 spellings, Count to int64, Update to Updates, Association calls to their v2 return values, and association_autocreate to Omit. Rewrite the association list queries with Offset and Limit as joins through the join tables with a matching Count so paging behaves the same. Change no behaviour beyond the migration; list any pre-existing bug you notice in the pull request instead of fixing it. Run go build ./..., go vet ./... and go test -v -race ./... until they pass, then open a pull request with a table of every v1 call and its v2 replacement.",
  "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 touches `go.mod`, `go.sum`, `db/db.go`, the two model files, both stores, the handler test, `.github/workflows/go.yml` and the `Dockerfile`. Its description carries a table with one row per v1 call site and the v2 line that replaced it, grouped by file, and quotes the `go test -v -race ./...` output from the sandbox so a reviewer sees the handler suite run against the migrated stores.

It separates the mechanical rows from the ones a reviewer should read: the `Updates` zero-value note, the `int64` count conversion at the store boundary, the rewritten join queries with the SQL GORM logged for each, and the pre-existing feed count it chose not to change. A reviewer checks those four, confirms the Go version bump is acceptable for the team's build images, and merges.

`dgrijalva/jwt-go` stays untouched, because it is outside the migration, and the pull request names it as the next dependency worth replacing.

## Run it on every Go service still on jinzhu/gorm

A team with several Go services sends this body once per repository from its own server. `GET /o/{org}/github` lists every repository the Rush GitHub App installation can reach, so a script fetches each `go.mod`, keeps the ones that require `github.com/jinzhu/gorm`, and sends one `POST /o/{org}/sessions` per match with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own stores: a service on Postgres gets `gorm.io/driver/postgres`, and one with no tests gets a note saying what was not verified.

An automation on the Project with a `linear` trigger on `linear.issue.labeled`, `tech-debt` in `config.labels`, and the prompt above starts one run per labelled issue once the first service has been migrated and the team wants the rest done the same way. The trigger adds the issue after the prompt and fills in no placeholder, so the issue body is where the team says which service and which database.

## Why run it on Rush?

A GORM v1 to v2 migration fails in a cascade: the first `go build` reports the import, the second reports the dozens of call sites behind it, and the real differences (an `int64` count, an error returned where a chain used to be, a struct tag silently ignored because its spelling changed) only show up when the tests run against a real database. The agent does that loop in its own sandbox, with sqlite, cgo and the right Go toolchain installed, and keeps every build and test run with the pull request.

A reviewer gets the before-and-after table and the SQL GORM logged for the rewritten queries rather than a diff to reverse-engineer. A team with many services starts the migration across all of them at once and reviews them as they arrive.

## Frequently asked questions

### Will my struct tags keep working if I miss one?

No, and that is the quiet failure in this migration: GORM v2 ignores a tag it does not recognise, so a leftover `unique_index` drops the unique index on the next `AutoMigrate`. The agent greps for every v1 tag spelling and the pull request table lists each one it changed, so a reviewer can confirm none remain.

### Does the Go version have to change?

In a module on Go 1.18, yes. `gorm.io/gorm` itself still declares `go 1.18`, but `gorm.io/driver/sqlite` declares `go 1.21`, and `go mod tidy` refuses a lower directive. The agent raises the directive, the workflow's `setup-go` version and the Dockerfile's build image together, and says which version it chose.

### What about the association queries with paging?

v1 let `Offset` and `Limit` sit in front of `Association(...).Find`. Rather than rely on how v2 carries those clauses into association mode, the agent writes the same queries as explicit joins through the join tables, with the count on the same query. The handler tests that page through articles by tag and by favourite are what prove the behaviour is unchanged.

### Will it switch the database driver too?

Only the GORM half of it. A sqlite app keeps `mattn/go-sqlite3` behind `gorm.io/driver/sqlite`, and a Postgres app gets `gorm.io/driver/postgres`. Changing the database itself is a different job.

## More Echo jobs

- [Upgrade Go Modules in an Echo App](https://getrush.ai/run/upgrade-go-modules/echo/)
- [Write Unit Tests for an Echo API](https://getrush.ai/run/write-unit-tests/echo/)
- [Add Response Compression to an Echo App](https://getrush.ai/run/add-compression/echo/)

## More jobs like this: Hand off a long task

- [Migrate a Gradle Build to the Kotlin DSL](https://getrush.ai/run/migrate-to-kotlin-dsl/gradle/)
- [Migrate a Gatsby Blog from Markdown to MDX](https://getrush.ai/run/migrate-to-mdx/gatsby/)
- [Migrate MkDocs API Docs From mkautodoc to mkdocstrings](https://getrush.ai/run/migrate-to-mkdocstrings/mkdocs/)

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