← Back to Good Intentions

Database Migrations in NTNT

A migration changes a database that already holds real data, and two things tend to go wrong. The database isn't in the state the code assumes, because someone changed it by hand or edited a migration after it ran. Or a change that worked on an empty test database fails on real rows. An agent writing the migration is exposed to both: it starts each session from the code, and the code can't tell it what the database really contains. Before 0.6, NTNT had no migration tool, and when we looked at 22 of our own apps we found four different homemade ways of running migrations. ntnt db replaces them with one tool built into NTNT.

How other tools approach it

Migration runners such as Flyway and Rails run migrations in order and record each one in a table. They're simple and predictable, but by default they trust that table, so a column someone added by hand goes unnoticed until something breaks.

Schema-first tools such as Prisma, Drizzle and Atlas's declarative mode start from a description of the schema the app should have and generate the SQL to get there. They usually notice drift, but the agent has to keep that description in step with the database, often in the tool's own language, and a generated change can't always tell a renamed column from a dropped one plus a new one.

What we chose

  • The agent writes plain SQL. There's no schema language, no ORM and no generated SQL, so what the agent writes is exactly what the database runs and what a reviewer reads. A rename is an ALTER TABLE ... RENAME, so there's nothing for a tool to guess.
  • The database works out the result. ntnt db plan replays the whole migration history on an empty scratch database running the same PostgreSQL or SQLite version, so NTNT doesn't need its own model of either database.
  • The real database is always checked. status, plan and verify compare it with what the history should have produced and name every difference. migrate refuses if the database changed after the plan was made.
  • Planning and approving are separate. The agent can plan a change, but migrate runs only the exact plan that was approved, against the database it was made for. There's no --force flag to reach for.
  • Checks run on real rows. The agent can attach SQL checks that run before and after a migration inside its transaction, such as "there are no duplicate emails" before adding a unique index. If a check fails, the whole migration rolls back.

A scratch database has a known risk: point it at the wrong database and replay can damage real data. Prisma 8 dropped its shadow database for that reason and works out migrations offline. We kept ours, because the real engine is the most reliable judge of what SQL does, and guard against that mistake instead: ntnt db refuses a scratch database that is really the target, whatever the connection string says, or that isn't empty, and it only cleans up what its own replay created.

Built with agents in mind

When a command fails, an agent tends to follow the error message. As Prisma's write-up puts it, "An agent's goal is a green exit code, so it does what the error says." So every ntnt db problem has a stable code and a next step that's safe to follow, and an outcome it can't confirm is reported as unknown instead of a guess. In production the approval comes from a secrets provider, so an agent without access to it can plan a change but can't approve it. The person who approves gets a plan that shows exactly what will run.

What it looks like

To start a SQLite project, the agent creates the configuration and its first migration:

ntnt db init --engine sqlite
ntnt db new create_posts

It writes the SQL in migrations/0001_create_posts.sql:

CREATE TABLE posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    tags TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(tags))
);

Then it plans the change, approves it and runs it:

mkdir -p data && touch data/app.sqlite data/replay.sqlite
export NTNT_ENV=development NTNT_SECRETS_PROVIDER=env
export APP_DATABASE_FILE="$(pwd -P)/data/app.sqlite"
export APP_REPLAY_FILE="$(pwd -P)/data/replay.sqlite"
ntnt db plan --target development --out plan.json
export APP_MIGRATION_APPROVAL="$(jq -r .plan_digest plan.json)"
ntnt db migrate --target development --plan plan.json
ntnt db verify --target development

On a development machine the agent can copy the approval straight from the plan, as it does here. If someone later adds a column to posts by hand, verify fails with DB_DRIFT and names the column, and the next plan stops, so the agent has to deal with the difference before it changes anything else.

Where intent comes in

With NTNT's intent files, the agent writes an app's requirements as scenarios, and ntnt intent check runs them against the real code. Today intent and ntnt db meet at the edges: a migration's checks prove it did what it promised when it ran, and lasting rules such as "emails are unique" belong in database constraints and intent scenarios.

We plan to connect them in two ways:

  • Intent tests against the real schema. The test runner will build a fresh database for each run with the same ntnt db executor, so a scenario like "a duplicate email is rejected" runs against the schema production has. This is part of DD-078.
  • A schema-aware language. NTNT will check the SQL in an app's queries against the schema the migrations produce, and link each table and column to the code and intent scenarios that use it. An agent planning a migration that drops a column would then see which features it breaks before anyone approves it, and a command like ntnt db explain users.email could say why the column exists. This is the third phase of the ntnt db design, and we'll settle its details once more apps have run on ntnt db.

Intent files won't contain SQL. Intent says what must be true, and changes to the database stay in migrations, under the same approval rules.

New in 0.6.5

0.6.5 adds what many real schemas need: SQLite AUTOINCREMENT and JSON functions, both used above, and PostgreSQL enums, domains and extensions such as citext. A database restored from a pg_dump backup now verifies too, and Jarri, one of our own apps, manages its PostgreSQL schema with ntnt db.

What to keep in mind

ntnt db doesn't cover every database feature yet. On PostgreSQL that includes materialized views, range types and foreign tables, and on SQLite, virtual tables and generated columns. Migrations take locks while they run, so changes to very large tables need planning, and ntnt db doesn't run backfills or take backups. When it finds something it can't check, it stops and names it instead of guessing.

The migrations recipe has a longer example, and the database guide covers PostgreSQL setup and production approvals.

← Live Updates in NTNT