Skip to content

Database migrations written with a coding agent: keep them additive and reviewed

Migrations change data that cannot be redeployed. Prefer additive steps, expand and contract, test on a copy, and have a person read every migration.

Published by Contextingo.

Code can be rolled back by deploying the old version. Data cannot. A migration written in a hurry is among the most expensive mistakes an agent can make.

Prefer additive changes

  • Add a column rather than rename or drop one.
  • Add a table rather than change one in place.
  • Make new columns nullable or give them a default so old code keeps working.

Expand and contract

To rename a column safely, do it in steps across several deploys:

  1. Add the new column.
  2. Write to both columns and backfill the old data.
  3. Switch reads to the new column.
  4. Stop writing the old column.
  5. Drop the old column in a later release.

Process

  • Run every migration against a copy of production-like data first.
  • Check lock behaviour and run time on large tables.
  • Keep migrations in version control, ordered and run by a separate step with the rights they need.
  • A person reads each migration before it is merged. Destructive statements get extra attention.
  • Take a backup before applying anything destructive.

In this project

Contextingo runs additive migrations in a separate job as the database owner, and the application never changes the schema at run time. Related: least privilege for coding agents.

Questions

Good to know.

Should an agent run migrations in production?

No. It can write them. A pipeline you control applies them after review.

Are down migrations needed?

They help in development. In production, forward fixes and backups are the safer rollback.

Nothing learned is lost. Nothing unchecked is done.