Skip to content

Databases and Changing a Live Schema

Summary

Explains tables, keys and queries, ORMs and migrations, and how to change a live database safely with backups, restore tests and one migration path.

Concepts Covered

This chapter covers the following 27 concepts from the learning graph:

Concept Concept Impact Score
Database 58
Relational Database 44
PostgreSQL 1
Table 42
Row and Column 1
Primary Key 5
UUID 2
Foreign Key 2
Relation 1
SQL Query 22
Transaction 1
Database Index 1
ORM 7
Drizzle ORM 1
Schema 12
Schema Change 11
Migration 6
Migration Tool 2
Migration Ordering 1
Idempotent Migration 1
Competing Migration Paths 1
Destructive Migration 1
Seed Data 1
Backup 12
Restore Test 10
Point-in-Time Recovery 1
Comparison Operator Bug 1

Prerequisites

This chapter builds on concepts from:


The Filing Cabinet in the School Office

Before computers, the front office of a small elementary school kept a gray filing cabinet behind the desk. Each drawer holds index cards, one card per student, filed by last name. Every card has the same printed lines: name, grade, teacher, parent, phone number. When a child gets sick at lunch, the secretary pulls the card and calls the number on it. Nobody thinks of the cabinet as anything special. It's just where the school keeps what it knows about its students.

One summer the district changes the rules. Every card now needs a second emergency contact, and the single "parent" line has to become two lines. But the school can't close while the cards get redone. Children still get sick in September.

Welcome to Chapter 11

Sawyer waving welcome Your database holds the one part of your app you can't rebuild from code. By the end of this chapter you'll be able to change it while people are using it, and get it back when a change goes wrong. Most schema changes are gates you can walk back through, and you'll learn to spot the few that are walls.

So the office staff work out a plan. First, someone photocopies every card and puts the copies in a box in the principal's closet. Then they add the new line to every card before anyone removes the old one, so a card is never missing a phone number. They tape a sheet to the cabinet that lists each step and who did it, so the afternoon secretary doesn't redo the morning's work. And one rule goes up on the wall in marker: nobody throws away an old card until the new one has been checked.

Months later, a pipe bursts over the cabinet. Only the photocopies in the closet tell the school whom to call. Someone pulls them out that afternoon and checks that they're readable.

That office did everything this chapter teaches. The cabinet is a database. The printed lines are the schema. The taped sheet is a migration log. The copies in the closet are a backup, and pulling them out to read them is a restore test. Your app's database works the same way, and your users depend on it the same way those families did.

What a Database Is

A database is an organized store of data that a program can read and change, and that keeps the data after the program stops. When the dating-safety app's server restarts, everything in its memory is gone. Members, scans, check results and payments survive because they live in the database. Chapter 3 named the database as one of the parts under your app. This chapter opens it up.

Two things make a database more than a big file. First, many requests can read and write it at the same moment without corrupting it. Second, it enforces rules about what the data may look like. A file will hold anything you write into it. A database can refuse a scan that has no member, or a trust score of 400.

That second point is why the database is a must-be-right part, in the language of Chapter 1. Almost everything else in the app can be rebuilt. You can redeploy the server, rewrite a screen or swap a vendor. The data members gave you can't be rebuilt from code. If a bad change deletes it, and no copy exists, it is gone for good.

Here is how the database compares with the other places an app keeps things:

Where data lives Survives a restart? Many requests at once? Enforces rules? Running example
Server memory No Only within one server No A scan's progress while its checks run
Storage bucket Yes Yes Only access rules Uploaded photos and voice clips
Database Yes Yes Yes Members, scans, check results, payments

The photos themselves sit in a private storage bucket, as Chapter 3 described. The database holds a row that says which bucket file belongs to which scan. That split is common: large files go in storage, and facts about them go in the database.

Relational Databases and PostgreSQL

A relational database stores data in tables that point at one another, and lets you ask questions that combine those tables. It is the most common kind of database behind web apps. Other kinds exist, such as document stores that hold loose bundles of fields. For an app that holds members, their scans and the results of each check, a relational database fits well, because those things are tightly linked and the links matter.

PostgreSQL, usually called Postgres, is a free, open-source relational database. It is the one the dating-safety app uses, hosted on Railway, and it is the one most AI coding agents reach first when you ask for a database. Many platforms host Postgres, so the habits in this chapter work on any of them.

An app finds its database through an address, which includes a password and usually sits in an environment variable named DATABASE_URL. Chapter 6 covers how to keep that value secret. Anyone who has it can read every member's data.

Tell your agent

"Tell me what database this app uses, where it's hosted, and which environment variable holds its address. Then list every place the app stores data that is not the database, such as storage buckets, files on disk or server memory. For each one, tell me whether that data survives a restart."

Tables, Rows and Columns

A table is a named set of records that all have the same shape. In this chapter's illustrative design, the dating-safety app has a members table, a scans table, a check_results table and a few more. Each table holds one kind of thing.

Inside a table, a row is one record, and a column is one field that every record has. Each row in scans is one scan. Each column is one fact about a scan: who asked for it, when, its status and its score. Rows come and go every minute. Columns change only when someone changes the design of the table.

Here is what a few rows of the scans table might look like. The IDs are shortened so they fit on the page.

id member_id status trust_score created_at
7f3a… c21e… complete 82 2026-10-02 14:05
91bd… c21e… complete 50 2026-10-03 09:41
0e6c… 4a90… running (empty) 2026-10-03 09:44

Read the table one row at a time and it tells three short stories. One member ran two scans a day apart. Its second scan scored a neutral 50, which in this app is what a scan gets when none of its checks could run, as Chapter 9 explained. A different member has a scan running right now, so it has no score yet.

Every column has a type, and the database enforces it. trust_score is a whole number, so the database rejects the word "high." created_at is a timestamp. A column can also be marked as required, so a row without that value is refused. A column can also have a default, such as status starting as pending. These rules are cheap to set and they catch mistakes before they become data. A trust score stored as text would sort "9" above "82," and every chart built on it would be wrong.

The trust_score cell in the third row is empty. A database calls an empty cell null. Null means "no value," which is different from zero. A score of zero says the match looks very risky. A null score says there's no score yet. Code that treats the two the same will tell a member something false, which is why the dating-safety app's rules about "not checked" reach all the way down into the column types.

Worked Example: Reading One Scan

Suppose a member writes to support and says, "My scan says 50, but I uploaded three photos." Here is how the tables answer the question.

  1. Find the member's row in members by email. Its id is c21e….
  2. Find that member's scans in scans, newest first. The scan from October 3 has a score of 50.
  3. Find that scan's rows in check_results. There are eight, one per check, and all eight say not_checked.
  4. Read the detail column on the photo check. It says the image-search vendor timed out.

The member's photos were stored. The checks ran and couldn't reach their vendors, so the score fell to the neutral 50, exactly as the product rule says it should. Four small lookups, each in one table, answered a question that would have taken an hour of guessing without them.

Tell your agent

"List every table in this app's database. For each table, give me one sentence on what a row means, the columns that are required, and any column that can be empty. Flag any column where empty and zero could be confused, such as a score or a count."

Keys: How Rows Find Each Other

A primary key is a column whose value is different in every row of a table, so it names exactly one row. In the scans table it is id. The database refuses a second row with the same id, and it refuses a row without one. Every table should have a primary key. Without one, there's no reliable way to say "change this row and no other."

There are two common ways to make primary keys. One is a counter: 1, 2, 3 and so on, with the database handing out the next number. The other is a UUID, short for universally unique identifier. A UUID is a 128-bit value, usually random, written as 32 hexadecimal digits (0 to 9 and a to f) in five groups, such as 7f3a9c2e-1b4d-4e8f-9a6b-2c5d8e1f0a37. Two machines can each make one without asking each other, and the odds of a clash are too small to matter.

Worked Example: Counter or UUID?

Take the link a member uses to open a result: /scans/1042. With counter keys, that link tells anyone who sees it three things.

  • The app has run about 1,042 scans, which a competitor may like to know.
  • Scan 1041 and scan 1043 probably exist.
  • Trying 1041 is a single keystroke.

If the server checks ownership on every request, as Chapter 7 requires, trying 1041 gets a "not found" and nothing leaks. But counter keys make guessing free, so one missed check exposes every scan in order. With UUID keys the same link is /scans/7f3a9c2e-1b4d-4e8f-9a6b-2c5d8e1f0a37. Nobody can guess the next one, and the link says nothing about how many scans exist.

UUIDs are a second lock, not a replacement for the first. They make a missing ownership check much harder to exploit, and they cost almost nothing. This chapter's illustrative design uses UUIDs for the main tables, and most agents will pick them if you ask.

Foreign Keys and Relations

A foreign key is a column in one table that holds the primary key of a row in another table. The member_id column in scans is a foreign key. It holds the id of the member who asked for the scan. The database checks it: it refuses a scan whose member_id doesn't match any member.

A relation is the link between two tables that a foreign key creates. People usually describe a relation by how many rows sit on each side. One member has many scans. One scan has many check results. Each check result belongs to exactly one scan. Saying it in that form, "one X has many Y," is enough to design most of an app's tables.

A foreign key also answers a question that matters a great deal for a safety app: what happens to the scans when a member is deleted? There are three common answers.

  • Refuse. The database won't delete a member who still has scans. Someone has to delete the scans first.
  • Cascade. Deleting the member deletes their scans, and deleting each scan deletes its check results.
  • Set to empty. The scans stay, with member_id set to null.

None of these is always right. For a member who closes their account, Chapter 8 says their private data should go, which points at cascade. For payment records, the law may require you to keep them, which points at refuse or set to empty. That choice is written into the foreign key, so it is worth making on purpose rather than taking the default your agent picked.

Use the diagram below to explore the tables in the dating-safety app and how they connect.

Diagram: Dating-Safety App Tables and Relations

Run the Dating-Safety App Tables and Relations MicroSim Fullscreen

Dating-Safety App Tables and Relations

Type: graph-model sim-id: safety-app-table-relations
Library: vis-network
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain, for each relation between five tables in the dating-safety app, which column is the foreign key and what happens to the child rows when a parent row is deleted.

Prerequisites: table, row, column, primary key, UUID, foreign key, relation, cascade, refuse and set-to-empty delete rules (all defined in the sections above).

Evidence of Mastery: After exploring, the learner answers five questions, one per relation, choosing which rows remain after a parent row is deleted. An answer is correct when it matches the delete rule on that relation in the Content table. Mastery is 4 of 5 correct on the first attempt.

Misconceptions: (1) Deleting a member always removes everything about them. (2) A foreign key is just a label and the database doesn't check it. (3) Every relation should cascade.

Instructional Rationale: Explaining a relation means stating what links two tables and what the link does under change. Clicking each node and edge, then predicting a deletion, makes the learner state the link and its effect instead of recognizing a picture.

Content:

Nodes (tables). Clicking a node shows its columns, with the primary key marked "PK" and foreign keys marked "FK".

Table Columns What one row means
members id (PK, UUID), email, created_at One person with an account
scans id (PK, UUID), member_id (FK to members), status, trust_score, created_at One request to check one match
uploads id (PK, UUID), scan_id (FK to scans), kind (photo, voice or text), storage_path One file or text the member gave for a scan
check_results id (PK, UUID), scan_id (FK to scans), check_name, result (passed, failed or not_checked), detail The outcome of one check on one scan
payments id (PK, UUID), member_id (FK to members), amount_cents, stripe_payment_id, created_at One charge through Stripe

Edges (relations). Clicking an edge shows the foreign key and its delete rule.

Edge Relation Foreign key Delete rule What happens when the parent row is deleted
members to scans one member has many scans scans.member_id cascade The member's scans are deleted
scans to uploads one scan has many uploads uploads.scan_id cascade The scan's upload rows are deleted
scans to check_results one scan has many check results check_results.scan_id cascade The scan's check results are deleted
members to payments one member has many payments payments.member_id set to empty Payment rows stay, with member_id empty

Quiz questions (asked after exploring):

# Question Correct answer Why (feedback)
1 A member is deleted. What happens to their scans? Deleted members to scans cascades.
2 A scan is deleted. What happens to its check results? Deleted scans to check_results cascades.
3 A member is deleted. What happens to their payments? Kept, with member_id empty Payment records may need to be kept, so this relation sets the key to empty.
4 A member is deleted. What happens to the check results on their scans? Deleted The cascade runs twice: member to scans, then scans to check_results.
5 Someone tries to add a scan whose member_id matches no member. What happens? The database refuses it A foreign key must point at an existing row.

Answer choices for every question: "Deleted," "Kept unchanged," "Kept, with member_id empty," "The database refuses it."

Provenance: The three check results, Postgres, Stripe and a private storage bucket come from the dating-safety app in research/seed-notes.md. Table names, UUID keys, the exact column lists and the delete rules follow the sections "Tables, Rows and Columns" and "Keys: How Rows Find Each Other," are illustrative, and must be labeled "illustrative design."

Rules: A cascade deletes child rows, and cascades chain through further cascades. Set-to-empty keeps the child row and empties the foreign key. An insert whose foreign key matches no parent row is refused.

Learner Activity:

  1. The learner sees five table nodes and four edges.
  2. The learner clicks any node to see its columns and any edge to see its foreign key and delete rule.
  3. A "Delete this row" button on members and on scans highlights every row that would be removed or changed, following the delete rules.
  4. When ready, the learner presses "Check my understanding" and answers the five questions.
  5. The learner should notice that deleting one member reaches three other tables.

Feedback: Five questions in the order listed, one attempt each. Correct: "Right. " plus the Why text. Incorrect: "Not quite. " plus the Why text, with the edge in question highlighted. Score "n of 5" shown at the end; "Mastery reached" at 4 or more.

Starting State: All five tables shown, nothing selected. The prompt reads "A member closes their account. Which rows go with them?"

Chapter Anchors: Three delete rules: refuse, cascade, set to empty. One member has many scans; one scan has many check results.

Tell your agent

"For every table, tell me its primary key and whether it's a UUID or a counter. Then list every foreign key, the relation it creates in the form 'one X has many Y,' and its delete rule. Tell me which deletions would leave a member's private data behind after their account is closed. Don't change anything yet."

Asking the Database Questions

A SQL query is a request written in SQL, the Structured Query Language, that asks a relational database to read or change data. SQL has been the common language of relational databases for about fifty years. Your agent writes it, often through a library, and you'll read more of it than you write.

Four kinds of query do almost all the work:

  • SELECT reads rows.
  • INSERT adds rows.
  • UPDATE changes rows that already exist.
  • DELETE removes rows.

The part that decides which rows a query touches is the WHERE clause. A SELECT without WHERE reads the whole table. An UPDATE or DELETE without WHERE changes or removes every row. That's the first thing to look for when you read a query your agent wrote.

Worked Example: A Member's Recent Scans

The results page needs a member's last ten scans, newest first. Here is the query. SELECT names the columns to return, FROM names the table, WHERE keeps only this member's rows, ORDER BY sorts them, and LIMIT stops after ten. The $1 is a placeholder that the server fills in with the signed-in member's ID.

SELECT id, status, trust_score, created_at
FROM scans
WHERE member_id = $1
ORDER BY created_at DESC
LIMIT 10;

The WHERE member_id = $1 line is doing two jobs. It picks the right rows, and it's also the ownership check from Chapter 7, written in SQL. Remove it and every member sees every scan. When you review a query that reads private data, look for the line that ties it to the signed-in member.

The placeholder matters too. The member's ID is passed to the database separately from the query text, so nothing a user types can change what the query does. Building a query by pasting user input into the text opens the door to SQL injection, which Chapter 16 covers.

Transactions

Some changes only make sense together. When a scan finishes, the app writes eight rows to check_results and then sets the scan's trust_score and its status to complete. If the server crashed halfway through, the scan could show a score with only five check results behind it. A member would see a number with only part of the evidence behind it.

A transaction is a group of database changes that succeed or fail as one unit. Either every change in the group is saved, or none of them is. You start a transaction, make the changes, and commit. If anything fails before the commit, the database rolls the whole group back as if it never started.

BEGIN;
INSERT INTO check_results (scan_id, check_name, result) VALUES (...);  -- eight rows
UPDATE scans SET trust_score = 82, status = 'complete' WHERE id = $1;
COMMIT;

Ask for a transaction whenever two or more writes have to agree with each other. Money is the classic case. Scores with their evidence is the dating-safety app's case.

Indexes

A database index is a sorted lookup structure that lets the database find rows by a column's value without reading every row. It works like the index at the back of a book. Without one, the query above reads every scan in the table to find one member's ten. With a thousand scans, nobody notices. With two million, the results page takes seconds.

CREATE INDEX IF NOT EXISTS scans_member_id_idx ON scans (member_id);

Primary keys get an index automatically. Postgres does not index foreign keys automatically, and the foreign keys are exactly the columns most queries filter on. Indexes aren't free: each one takes space and slows writes a little. A good default is an index on every foreign key and on any column a frequent query sorts or filters by.

Tell your agent

"Find every UPDATE and DELETE in this codebase, including ones written through the ORM. For each one, show me its WHERE condition and tell me how many rows it's meant to change. Then list any place where two or more writes must agree and aren't in a transaction, and any foreign key column that has no index."

The Comparison Operator Bug

One character in a WHERE clause can turn a careful change into a wide one. The dating-safety app had a scheduler that sends messages at set times. Chapter 10 used its bug to show how to reproduce a bug and keep it fixed with a test. Here is what went wrong inside the database. After it sent a message, it marked that message's row as sent so it wouldn't go out twice. The update compared IDs with <= where it should have used =.

A comparison operator bug is a mistake where a query or condition uses the wrong comparison, such as <= instead of =, so it matches more rows or fewer rows than intended. Nothing raises an error, and the query reports success. Only the data shows that anything went wrong.

Worked Example: One Send, Many Rows

Here is the queue of scheduled messages before the scheduler runs. The IDs and times are illustrative. Four messages are waiting to go out.

id send_at sent
101 09:00 false
102 09:30 false
103 10:00 false
104 10:30 false

At 10:00 the scheduler sends message 103. The vendor delivers it. Then the scheduler runs this update:

UPDATE scheduled_messages SET sent = true WHERE id <= 103;

The update matches rows 101, 102 and 103 and marks all three as sent. If 101 and 102 hadn't gone out yet, perhaps because the vendor was down at 9:00, they now never will. The scheduler thinks it has nothing left to send. No error appears anywhere, and the logs show one message sent and one update that succeeded.

The fix is one character: WHERE id = 103. With UUID keys the bug is stranger still. Postgres can compare UUIDs with <=, ordering them by their hex digits, so the update marks a random-looking scatter of rows as sent. That scatter is harder to spot, but just as wrong.

Two cheap habits catch this kind of bug, and both belong next to the fix.

  • Check how many rows changed. Every database returns a count of rows affected. An update meant to change one row should check that the count is exactly 1, and raise an error if it isn't.
  • Write a test with neighbors. Create three rows, send the middle one, and check that only the middle one is marked. A test with a single row can't see this bug, because "this row" and "every row up to this one" are the same when there's only one. Chapter 10 covers how to write tests like this.

Try different operators against the same queue in the sim below.

Diagram: One Character, Many Rows

Run the One Character, Many Rows MicroSim Fullscreen

One Character, Many Rows

Type: microsim sim-id: comparison-operator-rows
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: execute
Learning Objective: The learner will execute a WHERE condition against a six-row message queue and predict exactly which rows it changes, for five operators.

Prerequisites: row, primary key, SQL query, WHERE clause, UPDATE, rows affected, comparison operator bug (all defined in the sections above).

Evidence of Mastery: For each of five rounds, the learner selects the rows they predict the update will mark as sent, then runs it. A round is correct when the selected set equals the set the Rules produce. Mastery is 4 of 5 rounds correct on the first attempt.

Misconceptions: (1) An update that runs without error changed only the row you meant. (2) A test with one row proves the condition is right. (3) Rows already marked sent can't be harmed by a wider update.

Instructional Rationale: Applying a comparison means carrying it out on concrete rows. Predicting before running forces the learner to evaluate the operator row by row instead of reading the result after the fact.

Content:

Queue (synthetic, labeled "illustrative queue"):

id send_at sent before the update delivered by the vendor?
101 09:00 false No (vendor was down)
102 09:30 false No (vendor was down)
103 10:00 false Yes, just now
104 10:30 false No, not due yet
105 11:00 false No, not due yet
106 11:30 false No, not due yet

The scheduler has just delivered message 103. Rounds:

Round Condition Rows marked sent Rows wrongly marked Rows affected Why (feedback)
1 WHERE id = 103 103 none 1 Exactly the message that went out.
2 WHERE id <= 103 101, 102, 103 101, 102 3 Messages 101 and 102 never went out and now never will.
3 WHERE id < 103 101, 102 101, 102 2 It skips the message that did go out and marks two that didn't.
4 WHERE id >= 103 103, 104, 105, 106 104, 105, 106 4 Three future messages are canceled before they're due.
5 WHERE id != 103 101, 102, 104, 105, 106 all five 5 Every message except the one that went out is marked.

A toggle "Use a one-row test queue" replaces the queue with only row 103. In that mode, rounds 1 and 2 both mark only 103 with 1 row affected.

Provenance: The bug (a scheduler using <= instead of = on IDs so one send marked many rows as sent) is from research/seed-notes.md, Correctness row. Row IDs, times and vendor status are synthetic and must be labeled "illustrative."

Rules: A row is marked when its id satisfies the condition. Rows affected equals the number of rows marked. A row is "wrongly marked" when it is marked and its "delivered by the vendor?" value is not "Yes, just now." A check labeled "expect 1 row" shows a red error when rows affected is not equal to 1, and green when it equals 1.

Learner Activity:

  1. The learner reads the queue and the condition for round 1.
  2. The learner clicks the rows they predict will be marked, then presses Run.
  3. Marked rows turn to "sent"; wrongly marked rows are outlined. The rows-affected count and the "expect 1 row" check appear.
  4. The learner repeats for rounds 2 to 5.
  5. The learner switches on the one-row test queue and runs rounds 1 and 2 again, and should notice that the two conditions can't be told apart with one row.

Feedback: Five rounds in the listed order, one attempt each. Correct: "Right. " plus the Why text. Incorrect: "The update marked " plus the correct row list, plus the Why text. Score "n of 5" after round 5, with "Mastery reached" at 4 or more.

Starting State: The six-row queue with all rows unsent, round 1's condition shown, and the prompt "Message 103 just went out. Which rows will this update mark?"

Chapter Anchors: The bug is <= instead of =. The fix is one character. Two habits: check rows affected is exactly 1, and test with neighboring rows. A one-row test can't see the bug.

Tell your agent

"Search the code for every update or delete that is meant to change exactly one row. Show me the list and your plan before changing any of them. Then make each one check that it affected exactly one row and raise an error otherwise, and write a test for the message scheduler that creates three queued messages, sends the middle one, and checks that the other two are still unsent."

ORMs and Drizzle

Few apps built with an agent have raw SQL scattered through their code. Most use an ORM. An ORM, short for object-relational mapper, is a library that lets code describe tables and run queries using the app's own programming language, and turns that code into SQL. With an ORM, the agent writes TypeScript and the library writes the SQL.

ORMs bring three benefits. The table definitions live in code, so they're in git with everything else. Queries are checked by the type checker, so a misspelled column fails before the app runs. And the ORM fills in placeholders correctly, which shuts the door on most SQL injection.

Drizzle ORM is a TypeScript ORM, and it's the one the dating-safety app uses. Drizzle keeps close to SQL, so its code reads almost like the query it produces. Here is how the scans table looks in a Drizzle schema file. Each line names a column, its type, and its rules: primaryKey() marks the primary key, defaultRandom() makes a new UUID for each row, notNull() makes the column required, and references() makes a foreign key.

export const scans = pgTable("scans", {
  id: uuid("id").primaryKey().defaultRandom(),
  memberId: uuid("member_id").notNull()
    .references(() => members.id, { onDelete: "cascade" }),
  status: text("status").notNull().default("pending"),
  trustScore: integer("trust_score"),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

And here is the "recent scans" query from earlier, written with Drizzle. It produces nearly the same SQL you read above. The one difference is that an empty select() asks for every column, not just four.

const recent = await db.select().from(scans)
  .where(eq(scans.memberId, member.id))
  .orderBy(desc(scans.createdAt))
  .limit(10);

An ORM hides the SQL, and that is its one danger. The comparison operator bug looks just as harmless in Drizzle: lte(scheduledMessages.id, id) instead of eq(scheduledMessages.id, id). Most ORMs, Drizzle among them, can log the SQL they send. Turn that on in development, so you and your agent can read what the database receives.

Tell your agent

"Show me where this app's tables are defined in the ORM, and confirm that every table is defined in that one place. Turn on SQL logging in development only. Then pick the three queries that touch members' private data and show me the SQL each one sends."

Schema and Schema Change

A schema is the full description of a database's structure: its tables, their columns and types, keys, defaults, indexes and rules. It describes the shape of the data, not the data itself. The printed lines on the school's index cards were its schema. The handwriting on each card was the data.

In the dating-safety app, the schema lives in two places. One is the Drizzle schema file in the code. The other is the live database on Railway. They're supposed to match. When they don't, the app tries to read a column that isn't there, or writes a value the database doesn't expect, and it fails in ways that are hard to trace.

A schema change is any change to that structure: adding or removing a table or column, renaming something, changing a type, adding a key or an index. Changing the schema of an empty database is easy. Changing the schema of a live one is the job the school office faced. People are using it while you work, the data has to survive, and the old code and the new code may both run against it for a few minutes during a deploy.

Worked Example: Renaming a Score Without Losing It

Adding a column, such as a new confidence value that says how many checks ran, is an easy change. Nothing that exists has to move. Now take a harder one. Say the builder wants to rename trust_score to score to match the wording on the results page. A rename looks small. On a live database it's three risks at once.

  • The old server code, still running during a deploy, asks for trust_score and gets an error.
  • Some tools can't tell a rename from "drop one column and add another," and may write the second, which deletes every score.
  • Any report or script outside the app that reads trust_score breaks quietly.

A safer way is called expand and contract, and it's the same plan the school used for its cards. You add the new thing first, move to it, and remove the old thing last.

  1. Expand. Add the new score column. Leave trust_score alone. Nothing breaks, because nothing reads score yet.
  2. Copy. Fill score from trust_score for every existing row, and make new code write both columns.
  3. Switch. Change the code to read score. Deploy. Watch it for a day.
  4. Contract. Once nothing reads trust_score, and a fresh backup exists, remove it.

One wall, four gates

Sawyer thinking Notice what expand and contract does to the risk. Until the last step, you can undo every step by switching the code back, because the old column still holds everything. Only the contract step can't be undone, and by then you've watched the new column work for a day.

That's four steps where a rename is one. For a column that holds members' results, it's worth it. For a column nobody reads yet, a straight rename is fine. Save the extra care for columns that hold data people depend on.

Tell your agent

"Before you make any schema change, tell me whether it adds, removes, renames or changes the type of anything. If it removes, renames or changes a type on a table that has data, plan it as expand and contract: add the new column first, copy the data, switch the code, and leave removing the old column to a separate change that I approve."

Migrations: Schema Changes Written Down

A migration is a file that holds one schema change, written so a program can apply it to a database. Migrations are the taped sheet on the school's cabinet. Each one records a step. Together they record every change the schema has gone through, in order, and anyone can replay them to build the same schema from nothing.

A migration tool is the program that creates migration files and applies them to a database. Drizzle's tool is called drizzle-kit. When the schema file changes, drizzle-kit compares it with the last known schema and writes a new SQL file holding the difference, named so the files sort in the order they were made. A separate step applies any files the database hasn't seen yet.

A migration tool keeps track of what it has applied in a small table inside the database. Drizzle's is called __drizzle_migrations. Before it runs anything, the tool reads that table, compares it with the files on disk, and runs only the new ones. That is how a deploy knows which changes the production database still needs.

Migration ordering is the rule that migrations run in a fixed sequence, each one exactly once, because each change assumes the ones before it already ran. A migration that adds an index on scans.member_id will fail if the migration that creates member_id hasn't run. Tools keep the order by numbering the files or by putting a timestamp in the file name. Two people, or two agents on two branches, can each make "migration 0012" on the same day. When both branches merge, the order is unclear, and one of them may never run. Chapter 5's advice to keep branches short helps here more than anywhere.

Idempotent Migrations

An idempotent migration is one that leaves the database in the same state whether it runs once or several times. It's a word borrowed from mathematics, where it describes an operation that changes nothing the second time. The dating-safety app got this right: its migrations can run twice safely.

Here is the difference. The first line fails the second time it runs, because the column already exists. The second line does nothing the second time.

ALTER TABLE scans ADD COLUMN confidence integer;                -- fails on a second run
ALTER TABLE scans ADD COLUMN IF NOT EXISTS confidence integer;  -- safe to repeat

Postgres supports IF NOT EXISTS and IF EXISTS for most structural changes. Data changes can be made safe to repeat the same way, by writing WHERE score IS NULL so a second run skips rows already filled. Migrations rerun more often than you'd expect: a deploy that crashes partway and retries, a second server that boots at the same moment, a teammate's local database that's half up to date. An idempotent migration makes each of those harmless.

Run them twice

Sawyer giving a tip Here's a quick check. Make a fresh local database, apply every migration, then run each SQL file in the migrations folder against it again by hand, since the tool would skip them. Any file that errors on the second run isn't safe to repeat.

Seed Data

Seed data is a fixed set of starting rows loaded into a database so the app can run or be tested, such as a list of the eight check names, a test member, or sample scans. Seed data is useful in two places. In development and in staging (a private copy of the app for trying changes, which Chapter 14 covers), it gives a fresh database something to show, and gives tests a known starting point. In production, it fills tables the app needs before anyone signs up, such as a list of plans or check types.

Keep the two kinds apart. Test members and fake scans must never be loaded into production, where they'd show up in counts and could be shown to a member. Seed scripts that insert production rows should be idempotent too, inserting a row only if it isn't already there. And seed data must never be a copy of production members' data. Chapter 8 explains why private data doesn't belong in test environments.

Tell your agent

"Show me how this app creates and applies migrations, step by step, from a schema change to production. List the migrations in the order they run. Check each one and tell me whether it's safe to run twice. For any that aren't, show me how you'd make them safe, using IF NOT EXISTS, IF EXISTS or a WHERE condition that skips finished rows. Don't edit a migration that has already run in production without asking me first."

When Migrations Go Wrong

Migrations fail in quiet ways. A failed migration often doesn't stop the app. It leaves the database a little different from what the code expects, and the difference shows up days later as a bug in some other part of the app. The dating-safety app ran into two of these.

Check which database before a reset

Sawyer warning When a migration fails, agents often suggest resetting the database to clear the error. On your laptop that's fine, but against staging or production a reset deletes every row. Before you say yes, ask the agent which DATABASE_URL it will use, and fix the failing migration instead if that address isn't local.

Competing Migration Paths

Competing migration paths are two or more separate ways that schema changes reach the same database, with neither knowing what the other has done. In the dating-safety app, one path was the migration tool and its folder of files. The other was a block of SQL that the server ran each time it started up, which created or changed tables directly. Each path was reasonable on its own. Together, the database could end up in a state that neither of them described.

Here's why. The migration tool trusts its tracking table. If the startup SQL already added a column, the tool doesn't know, and its own migration that adds the same column fails. If the tool added an index, the startup SQL doesn't know, and may create a near copy of it under another name. Over months, the live schema drifts away from both the schema file and the migration folder. Nobody can rebuild it from either.

This pattern shows up in other forms too. Drizzle has a push command that applies the schema file straight to a database without writing a migration. It's handy on a laptop. Used against production alongside migrations, it's a second path.

The fix is a rule with one sentence: every schema change goes through one migration tool, and nothing else changes the structure of the database. Startup code may run the tool, which is common and fine. It may not run its own SQL. Chapter 17 covers the Schema Drift Check, an automated check that fails the build when the schema in code and the schema in the database disagree, so the rule enforces itself.

The Early Return

The second gap was in the startup code that ran migrations one after another. Somewhere in that sequence, a step could exit the whole function early. Code calls that an early return: a line that says "stop here and go back," often added to skip work that looks already done. When it fired, every migration after it was skipped. The server started normally and logged no error. The later tables and columns simply didn't exist in production.

Here is an illustrative sketch of the bug's shape. It is not the app's code. Each run call applies one change. The if near the top was meant to skip one step. It skips everything after it.

async function runStartupMigrations() {
  await run(createScansTable);
  if (await columnExists("scans", "status")) return;   // meant to skip one step
  await run(addStatusColumn);
  await run(createCheckResultsTable);                  // never runs once status exists
  await run(addScansMemberIndex);                      // never runs either
}

The fix for the line itself is to skip the one step instead of returning. The deeper fix is the one-path rule above: a migration tool runs every pending file and records each one, so no hand-written sequence can stop it short. A cheap check catches the rest. After migrations run, the app counts the migrations it applied and compares the number with the files on disk. If they differ, it refuses to start, and says why.

The simulator below runs a set of migrations under different conditions so you can see each of these failures happen.

Diagram: Migration Runner Stepper

Run the Migration Runner Stepper MicroSim Fullscreen

Migration Runner Stepper

Type: microsim sim-id: migration-runner-stepper
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: diagnose
Learning Objective: The learner will diagnose, from the final schema and the migration log, which of four failure conditions caused a production database to differ from the schema in code.

Prerequisites: schema, migration, migration tool, tracking table, migration ordering, idempotent migration, competing migration paths, early return (all defined in the sections above).

Evidence of Mastery: In four diagnosis rounds, the sim runs the migrations under one hidden condition and shows the resulting schema and log. The learner picks the condition from four choices. A round is correct when the pick matches the hidden condition. Mastery is 3 of 4 correct on the first attempt.

Misconceptions: (1) If the server started without errors, all migrations ran. (2) Running a migration twice is always harmless. (3) Two ways of changing the schema are safer than one.

Instructional Rationale: Diagnosing means working backward from a symptom to its cause. Letting the learner first run each condition openly, then face hidden ones, builds the link between cause and the shape of the damage it leaves.

Content:

Migrations in the folder, in order:

# Migration Change Idempotent version available?
1 0001_create_scans create table scans (id, member_id, created_at) Yes
2 0002_add_status add column scans.status Yes
3 0003_create_check_results create table check_results Yes
4 0004_add_member_index create index scans_member_id_idx Yes
5 0005_add_confidence add column scans.confidence Yes

Conditions the learner can switch on, one at a time:

Condition What happens Resulting schema Log shows
A. Healthy: one tool, idempotent files All five run once and are recorded Everything from 1 to 5 5 applied, 5 on disk
B. Early return after migration 2 Migrations 1 and 2 run; the runner exits scans with status; no check_results, no index, no confidence 2 applied, 5 on disk, no error
C. Rerun with non-idempotent files The deploy retries after migration 5 was applied but before it was recorded; migration 5 runs again Everything from 1 to 5 Error on 0005: column "confidence" already exists; server stops
D. Competing path: startup SQL also adds scans.confidence before the tool runs Migrations 1 to 4 run; 0005 fails because the column exists Everything from 1 to 5, but 0005 not recorded Error on 0005; tracking table shows 4 applied

A switch "Check applied count against files" is available in every condition. When on, the server refuses to start if the applied count is less than the number of files on disk, with the message "4 of 5 migrations applied. Refusing to start."

Diagnosis rounds (condition hidden): Round 1 = B, Round 2 = D, Round 3 = C, Round 4 = A.

Round Hidden condition Why (feedback)
1 B The log shows no error but only 2 of 5 applied. Something stopped the run early.
2 D The column exists but the tool didn't record adding it. Something else changed the schema.
3 C The column exists and the tool tried to add it again. The file wasn't safe to repeat.
4 A Applied count equals files on disk, and the schema matches.

Provenance: Competing migration mechanisms, the early return that skipped later migrations, and migrations that can run twice safely are from research/seed-notes.md. Migration names and the retry timing in condition C are illustrative and must be labeled "illustrative."

Rules: Migrations run in number order. A recorded migration is skipped. A non-idempotent "add" fails if the object exists; an idempotent one does nothing. An early return stops all later migrations without an error. The applied-count check compares rows in the tracking table with files on disk and blocks startup when they differ.

Learner Activity:

  1. The learner picks condition A and presses Step to apply one migration at a time, watching the schema panel and the tracking table fill.
  2. The learner repeats with conditions B, C and D, and notes how each one leaves the schema.
  3. The learner turns on "Check applied count against files" and runs B again, and should notice that the server now refuses to start instead of running with missing tables.
  4. The learner presses "Diagnose" to begin the four hidden rounds.

Feedback: Four rounds in the listed order, one attempt each. Correct: "Right. " plus the Why text. Incorrect: "This was condition [letter]. " plus the Why text, then the sim replays that condition step by step. Score "n of 4"; "Mastery reached" at 3 or more.

Starting State: Five migration files on the left, an empty database on the right, condition A selected, and the prompt "The server started with no errors. Did every migration run?"

Chapter Anchors: Two gaps from the dating-safety app: competing migration paths and an early return. One path rule: every schema change goes through one migration tool. The applied-count check refuses to start when applied and on-disk counts differ.

Destructive Migrations Are One-Way Doors

A destructive migration is a migration that removes or rewrites data in a way that can't be reversed from the database alone: dropping a table or column, changing a type in a way that cuts values short, or deleting rows. Chapter 1 called a decision you can't easily undo a one-way door. A destructive migration is one of the clearest one-way doors in software. Git can bring back the code that created a column, as Chapter 5 shows. Nothing in git can bring back the data that was in it.

Agents write destructive migrations for ordinary reasons. A column looks unused, so the agent drops it. A type looks wrong, so it changes text to integer and anything that doesn't convert is lost. A rename gets written as a drop and an add. Each change is small in the diff, and each one can remove months of members' data.

So destructive migrations get their own rules.

  • Name them. Have the agent mark any migration that drops, truncates or rewrites data, in the file and in the pull request.
  • Split them off. A destructive step goes in its own migration, separate from additions, so it can be reviewed and timed on its own. This is the contract step of expand and contract.
  • Back up first. Take a fresh backup, and confirm it exists, right before a destructive migration runs in production.
  • Try it on a copy. Run it against staging with realistic data first. Chapter 14 covers staging.
  • A person approves. An agent may write a destructive migration. It doesn't run one against production on its own.

Tell your agent

"Add a rule to this project's instruction file: any migration that drops a table or column, changes a column's type, renames anything, or deletes rows is destructive. Mark it DESTRUCTIVE at the top of the file, put it in its own migration, and stop to ask me before running it against production. Then check the existing migrations and list any destructive ones."

Backups and Getting Data Back

Every safeguard above makes a bad change less likely. None of them makes it impossible. A destructive migration with a typo, a DELETE without a WHERE, a cascade nobody expected, a hosting account that gets locked: any of them can empty a table. When that happens, only one thing matters, which is whether you can get the data back.

A backup is a copy of a database, taken at a known time and stored apart from it, that can be used to rebuild the data. Most hosted Postgres providers take automatic backups on some schedule. Plans and providers differ in how often they take them, how long they keep them, and how you restore one. The first job is to find out what yours does, because the default may be daily, weekly or nothing.

Two questions tell you whether your backups are good enough:

  • How much could you lose? If backups run once a day, a failure at 11 p.m. loses up to 23 hours of scans, sign-ups and payments.
  • Where do they live? A backup kept in the same account as the database is lost with the account. Keeping at least one copy somewhere else protects against that.

Restore Tests

A restore test is a practice run in which you rebuild a database from a backup, in a separate place, and check that the data is complete and the app can use it. It is the school secretary pulling out the photocopies to see if they're readable. A backup you've never restored is a guess. Files can be empty, cut short, encrypted with a key nobody kept, or missing the one table that matters. The only way to know is to restore one.

The seed notes for the dating-safety app list "a tested backup restore" among the cheap habits that would have caught gaps early. Here is what a first restore test looks like for the dating-safety app.

  1. Pick the most recent backup, and write down the time it was taken.
  2. Restore it into a new, empty database. Never restore over production as a test.
  3. Count rows in the main tables and compare them with production: members, scans, check results and payments.
  4. Open a few recent scans and check their check results are all there.
  5. Point a staging copy of the app at the restored database and sign in as a test member.
  6. Time the whole thing, from "start" to "the app works," and write it down.
  7. Delete the restored copy. It holds members' private data, and Chapter 8's rules apply to it too.

The time from step 6 is the number that matters most in an outage. If it took three hours on a quiet afternoon, it'll take longer at 2 a.m. under pressure. Write the steps into a runbook, which Chapter 18 covers, and repeat the test every few months or after any change to hosting.

Point-in-Time Recovery

Daily backups leave a gap. Say a destructive migration runs at 3:15 p.m. and drops a column. Last night's backup, taken at midnight, is more than fifteen hours old. Restoring it brings the column back and erases every scan and payment made since midnight.

Point-in-time recovery is a way of restoring a database to its exact state at any chosen moment within a recent window, such as 3:14 p.m. today. Postgres makes this possible by keeping a running log of every change, which the provider stores next to regular backups. To recover, it starts from the last full backup and replays the log up to the moment you pick. You get everything up to one minute before the mistake, and nothing after it.

Many hosted Postgres providers offer point-in-time recovery, often on paid plans and for a limited window, such as seven days. Check whether yours does and how far back it reaches. For an app that holds data people trust it with, it's usually worth the cost.

Diagram: Pick a Restore Point

Run the Pick a Restore Point MicroSim Fullscreen

Pick a Restore Point

Type: microsim sim-id: pick-a-restore-point
Library: p5.js
Status: Specified
Bloom Level: Evaluate
Bloom Verb: judge
Learning Objective: The learner will judge, for three data-loss incidents, which restore point recovers the most good data while excluding the damage, given daily backups alone or daily backups with point-in-time recovery.

Prerequisites: backup, restore test, point-in-time recovery, destructive migration (all defined in the sections above).

Evidence of Mastery: For each incident, the learner drags a marker on a one-day timeline to a restore point and states how many good writes are lost. A choice is correct when it is the latest allowed point strictly before the incident time, under the recovery mode shown. Mastery is 3 of 3 incidents correct, in at least one recovery mode each.

Misconceptions: (1) Restoring the latest backup is always right. (2) A backup from after the incident is fine as long as it's recent. (3) Point-in-time recovery means nothing is lost.

Instructional Rationale: Evaluating means choosing among options by a criterion. Each incident offers several legal restore points, and the learner must weigh lost good writes against restoring the damage.

Content:

The timeline runs from 00:00 to 24:00 on one day. A full backup exists at 00:00. Good writes (new scans, sign-ups and payments) arrive at a steady 40 per hour (synthetic).

Incident Time What happened
1 15:15 A destructive migration drops scans.trust_score
2 11:40 A DELETE without WHERE empties check_results
3 22:05 A cascade deletes 300 members' scans when a test script deletes members

Recovery modes:

Mode Allowed restore points
Daily backup only 00:00 only
Point-in-time recovery Any minute from 00:00 to the present, in 1-minute steps

Correct answers:

Incident Daily backup only Point-in-time recovery Good writes lost (daily) Good writes lost (PITR)
1 00:00 15:14 610 0
2 00:00 11:39 466 0
3 00:00 22:04 883 0

Provenance: Incidents are illustrative and must be labeled "illustrative scenario." The write rate of 40 per hour is synthetic. Point-in-time recovery's mechanism (full backup plus a replayed change log) is from the section "Point-in-Time Recovery."

Rules: Good writes lost = 40 per hour times the hours between the restore point and the incident time, rounded down to a whole number (15:15 minus 00:00 = 15.25 h, 610; 11:40 = 11.67 h, 466; 22:05 = 22.08 h, 883). Any restore point at or after the incident time restores the damage and is marked wrong with "This copy already has the damage in it." A point earlier than the latest allowed point before the incident is marked "Safe, but you lost more than you needed to," and counts as incorrect.

Learner Activity:

  1. The learner chooses a recovery mode.
  2. For each incident, the learner drags the restore marker and sees the count of good writes lost update as they drag.
  3. The learner presses Restore. The sim shows whether the damage is present and how much good data was lost.
  4. The learner switches modes and repeats, and should notice how much smaller the loss is with point-in-time recovery.

Feedback: Three incidents per mode, any order, one attempt per incident per mode. Correct: "Right. You lost " plus the count. Incorrect messages as in Rules, then the correct point is shown. "Mastery reached" when all three incidents are correct in at least one mode.

Starting State: Daily backup only selected, incident 1 shown on the timeline, marker at 00:00, and the prompt "A migration dropped a column at 3:15 p.m. Where do you restore to?"

Chapter Anchors: The worked case in the chapter is a migration at 3:15 p.m. with a midnight backup more than 15 hours old, and a restore to 3:14 p.m. with point-in-time recovery. A common recovery window is seven days.

Tell your agent

"Find out how this app's database is backed up: how often, how long backups are kept, where they're stored, and whether point-in-time recovery is on and for how many days. Write the answers in docs/backups.md. Then write a step-by-step restore test that restores the latest backup into a new database, compares row counts with production, and records how long it took. Don't run it against production."

A Safe Schema Change, From Start to Finish

Everything in this chapter fits into one routine. It's short enough to follow on every schema change, and the expensive steps only apply to the dangerous ones.

Step Every change Destructive changes only
Describe the change Agent says what it adds, removes, renames or retypes Marked DESTRUCTIVE
Write the migration One file, through the one migration tool, idempotent In its own file, as the contract step
Review the SQL Read the generated SQL, not only the ORM code Check every DROP, ALTER TYPE and DELETE by hand
Try it Run on a local or staging database Run on staging with realistic data
Protect the data Backups are on Fresh backup confirmed just before running
Apply to production Deploy runs pending migrations A person approves the run
Check Applied count matches files on disk Row counts checked after the run

Most of the first column is cheap, and much of it can be automated. Chapter 17 turns several of these rows into checks that run on every pull request, including the Schema Drift Check that compares the schema in code with the schema in the database.

Tell your agent

"Write a docs/schema-changes.md file for this project that holds the safe schema change routine: one migration tool, idempotent migrations, read the SQL, try on staging, fresh backup before anything destructive, my approval before a destructive migration runs in production, and an applied-count check at startup. Add a line to the instruction file telling every agent to follow it."

Back to the Filing Cabinet

The school office never used words like schema or migration. Its staff could see the cabinet and touch the cards, and everyone knew a card thrown away was gone for good. A database hides all of that. You can't see a column being dropped, and nobody hears a backup fail. The habits in this chapter put back what the cabinet made obvious. Chapter 12 picks up the next question: how you'd find out that something had gone wrong at all.

Your data has a way back

Sawyer celebrating You can now plan a schema change that keeps members' data safe: one migration tool, expand before contract, and a backup you've proven by restoring it. That's one of the hardest parts of running an app, and you can do it on purpose now. Good enough for now, and you know why.

Key Takeaways

  • A database holds the data an app can't rebuild from code, so it's a must-be-right part. PostgreSQL stores it in tables of rows and columns, linked by primary keys and foreign keys.
  • A foreign key's delete rule decides what happens to a member's data when they leave. UUIDs make keys unguessable.
  • The comparison operator bug used <= instead of =, so one send marked many rows. Check rows affected, and test with neighboring rows.
  • Every schema change goes through one migration tool, in order. Expand first, contract last, and make each migration safe to run twice.
  • A destructive migration is a one-way door. Back up first and have a person approve it.
  • A backup counts only once a restore test has shown it works.

See Annotated References