Updated Nov 25, 20269 min read

Let AI Coding Agents Write Database Migrations Safely

How a coding agent can change your database schema without touching production by hand: migrations as reviewed files, a real Postgres locally, a fresh database in tests, a database per pull request, and expand and contract for anything destructive.

Illustration for Let AI Coding Agents Write Database Migrations Safely

AI coding agents write more of the backend every month, and a schema change is where a mistake costs the most. Code can be rolled back in a minute, but a dropped column or a table locked during peak traffic cannot.

This guide covers the failure modes that matter, the guardrails that stop them, and a Go example where an agent ships a schema change through review, tests and a per-PR database without ever holding production credentials.

What goes wrong when an agent changes the database?

In July 2025 a Replit agent deleted a production database during a declared code freeze, then claimed the data could not be restored. Replit responded by separating development and production databases by default, so the agent can no longer touch production while it works. The lesson generalizes: the problem was not the SQL the agent wrote, it was that the agent had a live connection to production at all.

With that removed, the remaining failures come from migrations that look correct and still break things:

FailureWhat it looks likeWhat catches it
Destructive change in one stepRenaming or dropping a column the running release still readsExpand and contract across releases
Long lock on a hot tableALTER TABLE waits behind a long query, and every query behind it waits toolock_timeout in the migration
Table rewriteChanging a column type, which rewrites the table and its indexesReview, plus a test on realistic data
Edited historyThe agent changes a migration that already ran, so environments driftA rule that applied migrations are never edited
Constraint that fails on real dataA UNIQUE or NOT NULL that passes on an empty local tableA per-PR database copied from staging

The PostgreSQL ALTER TABLE docs list which changes rewrite the table: adding a column with a volatile default or changing a column type rewrites the table and its indexes, while adding a nullable column with no default only touches the catalog.

What guardrails should be in place?

The goal is that every schema change an agent makes goes through the same path a careful engineer's would, and that the path itself does the checking:

  1. Migrations are files in the repository. The agent writes a new numbered file next to the code that needs it, and a person reviews both in one pull request.
  2. No production credentials in the agent's environment. The deploy pipeline applies migrations; nothing on a laptop or in a CI job the agent controls can connect to production.
  3. A real Postgres locally. The agent runs the migration against the same engine and version as production, so syntax and lock behavior match.
  4. A fresh database in tests. The suite applies the full migration history from zero on every run, which catches broken ordering and edited history.
  5. A database per pull request. A preview environment applies the migration to a copy of staging data, which is where constraints meet real rows.
  6. Expand and contract for anything destructive. Add the new column, write to both, backfill, switch reads, then drop the old column in a later release.
  7. Short lock timeouts. Each migration sets lock_timeout, so a blocked ALTER TABLE fails fast instead of stalling the table.

Rules 2 to 5 are infrastructure, and they are the hard part to build yourself: a migration runner wired into deploys, a test database per run and a database per pull request, with the credentials split between them.

How does Encore handle migrations from AI agents?

Encore is the safe way for AI agents to ship backend changes to your cloud. The database is declared in the service code with infrastructure from code, so an agent adds a migration and the code that uses it in the same change, and Encore applies the migrations on encore run, on a fresh database in encore test and on every deploy to your AWS or GCP account.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

If a migration fails during a deployment, the deployment is aborted and the migration rolled back, as the schema change docs describe.

The agent never needs a connection string: locally, encore run starts Postgres and applies the migrations for it, and in the cloud each service connects with its own credentials that Encore manages. When someone does need to look at a cloud database, encore db shell opens a read-only session unless a write flag is passed, according to the CLI reference.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create accounts-app --example=hello-world$ cd accounts-app && mkdir -p accounts/migrations

The starting schema

The accounts service starts with a full_name column. The product now wants a separate display name, and the agent is asked to add it:

-- accounts/migrations/1_create_accounts.up.sql CREATE TABLE accounts ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL UNIQUE, full_name TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- Sessions issued by your identity provider. Store a hash of the bearer token, -- never the token itself, and reject expired or revoked rows. CREATE TABLE sessions ( token_hash TEXT PRIMARY KEY, account_id BIGINT NOT NULL REFERENCES accounts (id), expires_at TIMESTAMPTZ NOT NULL, revoked_at TIMESTAMPTZ );

The expand migration the agent writes

A careless version renames full_name to display_name in one step, which breaks the release still running during the rollout. The expand step adds a nullable column and leaves the old one alone:

-- accounts/migrations/2_add_display_name.up.sql -- Expand step: add the new column without touching the old one. -- Give up quickly instead of queueing behind a long transaction and blocking every query on the table. SET lock_timeout = '5s'; -- A nullable column with no default is a metadata-only change, with no table rewrite. ALTER TABLE accounts ADD COLUMN display_name TEXT;

The code change in the same commit

Reads fall back to full_name for rows written before the migration, and writes go to both columns so the previous release still reads correct data:

// accounts/accounts.go package accounts import ( "context" "crypto/sha256" "encoding/hex" "errors" "strconv" "strings" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) // Migrations in ./migrations are applied by `encore run`, by `encore test` on a fresh // database, and on every deploy, where a failing migration aborts the deployment. var db = sqldb.NewDatabase("accounts", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Account struct { ID int64 `json:"id"` Email string `json:"email"` DisplayName string `json:"display_name"` } func sessionHash(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } //encore:authhandler func AuthHandler(ctx context.Context, token string) (auth.UID, error) { if token == "" { return "", &errs.Error{Code: errs.Unauthenticated, Message: "missing auth token"} } var accountID int64 err := db.QueryRow(ctx, ` SELECT account_id FROM sessions WHERE token_hash = $1 AND expires_at > now() AND revoked_at IS NULL`, sessionHash(token)). Scan(&accountID) if errors.Is(err, sqldb.ErrNoRows) { return "", &errs.Error{Code: errs.Unauthenticated, Message: "unknown, expired or revoked session"} } if err != nil { return "", err } return auth.UID(strconv.FormatInt(accountID, 10)), nil } func requireAccount(id int64) error { uid, ok := auth.UserID() if !ok || string(uid) != strconv.FormatInt(id, 10) { return &errs.Error{Code: errs.PermissionDenied, Message: "not your account"} } return nil } //encore:api auth method=GET path=/accounts/:id func Get(ctx context.Context, id int64) (*Account, error) { if err := requireAccount(id); err != nil { return nil, err } a := &Account{ID: id} // During the expand phase, rows written before migration 2 only have full_name. err := db.QueryRow(ctx, ` SELECT email, COALESCE(display_name, full_name) FROM accounts WHERE id = $1`, id). Scan(&a.Email, &a.DisplayName) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "account not found"} } return a, err } type SetDisplayNameParams struct { DisplayName string `json:"display_name"` } //encore:api auth method=PATCH path=/accounts/:id/display-name func SetDisplayName(ctx context.Context, id int64, p *SetDisplayNameParams) error { if err := requireAccount(id); err != nil { return err } name := strings.TrimSpace(p.DisplayName) if name == "" || len(name) > 80 { return &errs.Error{Code: errs.InvalidArgument, Message: "display_name must be 1 to 80 characters"} } // Write both columns until the contract migration drops full_name, // so the previous release keeps reading correct data during the rollout. res, err := db.Exec(ctx, ` UPDATE accounts SET display_name = $2, full_name = $2 WHERE id = $1`, id, name) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.NotFound, Message: "account not found"} } return nil }

A test that runs the whole migration history

The agent adds a test that writes a row the old way and checks it reads correctly before and after an update. Running it with encore test applies every migration to a fresh test database first, as the testing docs explain, so a migration that does not apply cleanly fails the run:

// accounts/accounts_test.go package accounts import ( "context" "strconv" "testing" "encore.dev/beta/auth" ) // encore test applies every migration to a fresh test database before this runs, // so a migration that does not apply cleanly fails the test run. func TestDisplayNameAcrossTheMigration(t *testing.T) { // A row written the old way, as if it existed before migration 2. var id int64 if err := db.QueryRow(context.Background(), ` INSERT INTO accounts (email, full_name) VALUES ('ada@example.com', 'Ada Lovelace') RETURNING id`). Scan(&id); err != nil { t.Fatal(err) } ctx := auth.WithContext(context.Background(), auth.UID(strconv.FormatInt(id, 10)), nil) a, err := Get(ctx, id) if err != nil || a.DisplayName != "Ada Lovelace" { t.Fatalf("old row: got %+v, %v", a, err) } if err := SetDisplayName(ctx, id, &SetDisplayNameParams{DisplayName: "Ada"}); err != nil { t.Fatal(err) } a, err = Get(ctx, id) if err != nil || a.DisplayName != "Ada" { t.Fatalf("after update: got %+v, %v", a, err) } }

Review on a copy of real data

When the agent opens the pull request, Encore creates a preview environment for it with its own database and applies the migration there. With Neon as the database provider, that database starts as a copy of staging, so a constraint that only fails on real rows fails in the pull request instead of in production.

Contract in a later release

Once every row has a display_name and no deployed code reads full_name, a later pull request backfills the remaining rows, adds NOT NULL and drops the old column. The expand and contract guide covers the backfill and constraint steps in detail.

Write the rules down for the agent

Agents follow written rules more reliably than conventions they have to infer. A few lines in AGENTS.md or CLAUDE.md cover the cases above:

Database migrations: - Add a new numbered file in <service>/migrations; never edit a migration that is already merged. - Never rename or drop a column in one step; add the new column, write both, and drop in a later PR. - Start every migration that alters an existing table with SET lock_timeout = '5s'; - Run encore test before opening the PR and fix any migration error it reports.

Best fit: Teams that let coding agents work on the backend and want schema changes to go through review, tests and a per-PR database, with production credentials kept out of reach.

Which setup should you use?

If you already run a migration tool with a CI pipeline, a test database per run and separate production credentials, keep it, and add the written rules and lock timeouts. Use Encore when you want those guardrails without building them, so an agent can add a table or a column and the code that uses it in one reviewed change that is tested locally, in a per-PR environment and on deploy.

Frequently asked questions

Should an AI coding agent have access to the production database?

The agent should not hold production credentials at all, and should change the schema by writing migration files in the repository, which a person reviews in the pull request and the deploy pipeline applies. Give it a local database and a per-PR copy to test against, and keep production credentials with the deploy system.

How do I stop an AI agent from dropping a table?

Do not give it a connection that can drop anything outside your machine, and review every migration file in the pull request. Write in your AGENTS.md or CLAUDE.md that applied migrations are never edited and that drops and renames go through expand and contract across separate releases.

How do I test a migration an AI agent wrote?

Apply it to a real Postgres, not a mock: run the full migration history on a fresh database in your test suite, then on a database per pull request with a copy of staging data. That catches syntax errors, failed constraints and schema drift before production.

How does Encore handle migrations written by AI agents?

Encore applies the numbered migration files in each service on encore run, on a fresh database in encore test, and on every deploy, and it aborts a deployment when a migration fails. The agent writes the migration and the code in one change, and it never needs a production connection string.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders