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.

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.
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:
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.
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:
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.
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.

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.
Run in your terminal to get started locally.
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
);
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;
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
}
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)
}
}
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.
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.
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.
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.
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.
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.
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.
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.