# Add Versioned Database Migrations to an Echo App

Yes. An agent replaces AutoMigrate at startup in your Echo app with versioned gormigrate migrations, keeps a fresh database working, runs the tests and opens a PR.

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

## What the agent does

In a service like xesina/golang-echo-realworld-example-app, `main.go` opens the database with `db.New()` and calls `db.AutoMigrate(d)` before the handlers are registered; `db/db.go` opens `./realworld.db` through `github.com/jinzhu/gorm` with the SQLite dialect and `LogMode(true)`, and `AutoMigrate` passes `User`, `Follow`, `Article`, `Comment` and `Tag` to GORM with a `//TODO: err check` above it. The models in `model/` embed `gorm.Model`; `User` has `unique_index` on `Username` and `Email`, `Follow` a composite primary key of `FollowerID` and `FollowingID`, `Article` a `unique_index` on `Slug` and two `many2many` tables, `favorites` and `article_tags`, and `Comment` carries `ArticleID` and `UserID` with no index tag. The handler tests do the same thing as `main`: `TestMain` in `handler/handler_test.go` opens `./../realworld_test.db` with `db.TestDB()`, calls `db.AutoMigrate`, loads fixtures, and `tearDown` deletes the file. `go.mod` says `go 1.18` with `jinzhu/gorm v1.9.8` and `mattn/go-sqlite3` pulled in indirectly, the `Makefile` runs `go test -v -race ./...`, and `.github/workflows/go.yml` builds and tests on Go 1.18.

The agent chooses `gopkg.in/gormigrate.v1`, the gormigrate line written for `jinzhu/gorm`, and adds `db/migrate.go` with one exported function, `Migrate(db *gorm.DB) error`. It builds `gormigrate.New` with `UseTransaction: true`, since SQLite runs DDL inside a transaction, an `InitSchema` function, and a slice of migrations with timestamped IDs, each with a `Migrate` and a `Rollback`. gormigrate treats a database with no recorded migration as fresh: it runs `InitSchema` and then records every ID in the slice as applied. So `InitSchema` must produce the final schema, which the agent writes as the existing `AutoMigrate` call followed by the same index statements the versioned migrations add. An existing `realworld.db` created by the old code has no `migrations` table either, so it takes the same path, and that is harmless because `AutoMigrate` only adds what is missing and the indexes are created with `IF NOT EXISTS` semantics through GORM's `AddIndex` after a check.

The first versioned migration is real work rather than a placeholder: indexes on `comments.article_id` and `comments.user_id`, the columns that `GetCommentsBySlug` in `store/article.go` reaches through `Preload("Comments")` and `Preload("Comments.User")`, with a `Rollback` that drops them with `RemoveIndex`. `main.go` calls `db.Migrate(d)` and exits through `r.Logger.Fatal` on an error instead of ignoring one, and `handler_test.go` calls the same function in `setup`, so the test database is built by the migrator from now on and a migration that breaks the schema fails `go test` before it reaches a deployment. `AutoMigrate` stays in `db.go` as the body of `InitSchema` only; nothing else calls it.

The agent runs `go build ./...`, `go vet ./...` and `go test -race ./...` in its sandbox, where the SQLite driver's cgo build has a compiler, and then starts the server twice: once against no database file, reading the `LogMode(true)` output to see the `CREATE TABLE` statements followed by the two `CREATE INDEX` statements and the rows inserted into `migrations`, and once against a copy of a database the old `AutoMigrate` made, to see only the index statements and the same rows. It queries the `migrations` table with the `sqlite3` CLI for both and pastes the rows. `go mod tidy` adds the one new requirement to `go.mod` and `go.sum`; the Swagger annotations, `docs/` and the handlers are untouched, and the pull request lists every file and the two startup logs.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add versioned database migrations to this Echo app. Read main.go, db/db.go, every file in model/ and store/, handler/handler_test.go, go.mod, the Makefile and .github/workflows/go.yml first. Use the gormigrate line that matches the GORM version in go.mod. Write db/migrate.go with a Migrate function: an InitSchema that builds the final schema for a fresh database, and a slice of versioned migrations with rollbacks, starting with indexes on the comment table's article and user foreign keys. Run migrations in a transaction. Replace the AutoMigrate calls in main.go and the test setup with Migrate, and return the error instead of ignoring it. Run go build, go vet and go test -race, start the server against an empty database and against one made by the old AutoMigrate, show the migration log and the rows of the migrations table for both, and open a pull request with 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 adds `db/migrate.go` and changes `main.go`, `db/db.go`, `handler/handler_test.go`, `go.mod` and `go.sum`. Its description shows the `Migrate` function, the first migration with its rollback, the two startup logs side by side, the `migrations` rows from each database, and the `go test -race` output.

The `Go` workflow runs on the pull request with its build and test steps, so a reviewer sees the handler tests pass against a test database the migrator built. The run's record keeps both server starts, the `sqlite3` queries and the `go vet` output.

Before merging, a reviewer decides whether migrations should keep running at startup or move behind a flag or a `make migrate` target for production, and whether the `go` directive or the CI Go version needs to move for the new module. The models, the stores and the API are unchanged.

## Run it on every Linear issue labelled agent

A team that tracks schema work in Linear adds an automation on the Project with a `linear` trigger on issues labelled `agent` and this prompt. When an issue such as "add an index on comments.article_id" gets the label, a run starts in the repository, reads `db/migrate.go`, appends a migration with the next timestamp and a rollback, runs the tests and the two startup checks, and opens a pull request that links the issue. The trigger adds the issue after the prompt, so one prompt serves every issue.

The same body sent to `POST /o/{org}/sessions` by hand, with a `request_id` that is a UUID v5 of the issue's identifier, does the same for a one-off. The key's `webhook_url` reports each run the key starts with the pull request in `result`; a run an automation starts is reported in the Project's run list and has its own `max_runs_per_hour` cap.

## Why run it on Rush?

Moving from `AutoMigrate` to versioned migrations is a small diff with one trap: the migrator's idea of a fresh database and the databases that already exist. The agent reads how gormigrate records its first run, writes `InitSchema` so that an old database and an empty one end in the same state, and proves it by starting the server against both in its own sandbox with the SQL log on.

The two startup logs, the `migrations` rows and the race-enabled test run stay with the run and are quoted in the pull request. A team with several Go services on `jinzhu/gorm` gets the same change per repository, each checked against that repository's own models and tests.

## Frequently asked questions

### What happens to a database that AutoMigrate already created?

It has no `migrations` table, so gormigrate treats it as fresh and runs `InitSchema`, which calls `AutoMigrate` and adds the indexes. `AutoMigrate` creates only what is missing, so the tables are untouched, the indexes are added, and every migration ID is recorded. The agent shows exactly this by starting the server against a copy of such a database.

### Why gormigrate and not golang-migrate with SQL files?

Because the schema is defined by GORM struct tags and the app uses `jinzhu/gorm`, which gormigrate's v1 line targets; a migration can call `AutoMigrate`, `AddIndex` or raw SQL on the same `*gorm.DB`. SQL files would mean maintaining the schema twice. If the team later moves to `gorm.io/gorm`, gormigrate's v2 line has the same API.

### Do the handler tests still work?

Yes. `setup` calls `db.Migrate` where it called `db.AutoMigrate`, and `tearDown` still deletes `realworld_test.db`, so every `go test` run starts with an empty file and exercises `InitSchema`. A migration that fails makes `setup` fail, which stops the suite with the migrator's error.

### Can migrations run separately from the server?

The pull request keeps them at startup, as `AutoMigrate` was, so nothing changes operationally. The description shows a `migrate` subcommand or flag that calls `db.Migrate` and exits, and a `RollbackLast` helper, as the next step if deployments should migrate before the new binary starts serving.

## More Echo jobs

- [Add Dependabot to an Echo App](https://getrush.ai/run/add-dependabot/echo/)
- [Add golangci-lint to an Echo API's CI](https://getrush.ai/run/add-golangci-lint-to-ci/echo/)
- [Add Graceful Shutdown to an Echo App](https://getrush.ai/run/add-graceful-shutdown/echo/)

## The same job on other stacks

- [Add Versioned Database Migrations to a Gin App](https://getrush.ai/run/add-database-migrations/gin/)
- [Add Database Migrations to a GORM App](https://getrush.ai/run/add-database-migrations/gorm/)
- [Add Knex Migrations to an Express App](https://getrush.ai/run/add-database-migrations/knex/)

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