Module 04 · Lesson 4.2
Database Schema and Migrations
On this page
- What you will learn
- What a schema and a migration are
- The Tidewell migration files
- Run the migrations and prove the rule
- Review generated SQL before you apply it
- Step-by-step workflow
- Assistants and SQL: where the lines are
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A building keeps a renovation log. Each entry is numbered and says what the builders changed: add a wall, move a door. Nobody rewrites an old entry, because the work is already done. A database needs the same kind of log, and it is called a set of migrations.
In this lesson you turn the Tidewell data model into three numbered SQL files. You run them in order on a real PostgreSQL engine and watch the database refuse a double booking, with the exact error message. You then learn how to review SQL that an assistant wrote, before it touches any data.
What you will learn
- Write a schema as numbered SQL migration files and explain why applied files are never edited.
- Run migrations in order and record which ones have been applied.
- Prove a database rule by breaking it on purpose and reading the error.
- Review generated SQL with a checklist before applying it.
Before you start
- Completed Modelling Entities and Relationships, or have a data model of your own.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
What a schema and a migration are
The schema is the blueprint of a database: its tables, columns, links and rules. A migration is one numbered file that changes the schema from one state to the next. Put the files in order and you can rebuild the whole database from nothing, on any computer.
- Migration
- A numbered SQL file that makes one change to the schema. It is one entry in the renovation log.
- Applied
- A migration that has already run on a given database. Each database keeps its own tick-list.
- schema_migrations
- A small table that lists the migrations a database has run, so none runs twice.
- Transaction
- A group of steps that either all happen or none do, like a bank transfer that must both take and give the money.
- PostgreSQL
- The database Tidewell uses. It is free, widely used and well documented.
The golden rule is: never edit a migration that has been applied. Other copies of the database, such as a teammate's laptop or the live system, have already run the old text. If you change it, they no longer match. Add a new numbered file that makes the change instead.
Tools such as node-pg-migrate, Prisma Migrate, Drizzle Kit and Flyway do this work for you. They differ in language and style, and each is a fair choice. This lesson uses plain files and a short runner, so you can see exactly what a tool does for you.
The Tidewell migration files
Module 3 reserved the folder db/migrations for three files. The first holds the tables that exist before anyone books anything: clinicians, patients and slots.
CREATE TABLE clinicians (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
display_name text NOT NULL,
active boolean NOT NULL DEFAULT true
);
CREATE TABLE patients (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name text NOT NULL,
email text NOT NULL UNIQUE,
phone text
);
CREATE TABLE slots (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
clinician_id bigint NOT NULL REFERENCES clinicians (id),
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
CHECK (ends_at > starts_at),
UNIQUE (clinician_id, starts_at)
);GENERATED ALWAYS AS IDENTITYmakes the database hand out the next id number itself. You cannot type one in by mistake.NOT NULLmeans a value is required.textholds any length of text.timestamptzstores an exact moment in time. PostgreSQL saves it in UTC, the world's reference time, and converts it to your time zone when you read it, so '9:00 in London' and '9:00 in Paris' are never confused.REFERENCES clinicians (id)is the foreign key. A slot cannot name a clinician that does not exist.CHECK (ends_at > starts_at)stops a slot from ending before it starts.UNIQUE (clinician_id, starts_at)stops one clinician from having two slots that begin at the same moment.
The second file holds the heart of the system: bookings, the rule against double booking and the change history.
CREATE TABLE bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slot_id bigint NOT NULL REFERENCES slots (id),
patient_id bigint NOT NULL REFERENCES patients (id),
status text NOT NULL CHECK (status IN ('booked', 'cancelled')),
created_at timestamptz NOT NULL DEFAULT now(),
cancelled_at timestamptz
);
-- NFR-01: at most one live booking per slot.
CREATE UNIQUE INDEX one_live_booking_per_slot
ON bookings (slot_id)
WHERE status = 'booked';
-- FR-05: rows are only ever added, never changed.
CREATE TABLE booking_changes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
booking_id bigint NOT NULL REFERENCES bookings (id),
action text NOT NULL CHECK (action IN ('created', 'moved', 'cancelled')),
actor_role text NOT NULL CHECK (actor_role IN ('patient', 'staff')),
actor_id bigint NOT NULL,
from_slot_id bigint REFERENCES slots (id),
to_slot_id bigint REFERENCES slots (id),
changed_at timestamptz NOT NULL DEFAULT now()
);CHECK (status IN ('booked', 'cancelled'))lists the only two allowed statuses.CREATE UNIQUE INDEX ... WHERE status = 'booked'is the partial unique index from the last lesson. Among live bookings, a slot id can appear only once. Cancelled rows are ignored.booking_changesstores one row per change: the action, who did it (a role and an id) and when. Nothing in this table is updated or deleted by the application, so the history stays true.from_slot_idandto_slot_idmay be empty, because a new booking has no 'from' and a cancellation has no 'to'.
The third file adds the waiting list for FR-03. It is short, so you can read all of it at once. An empty clinician_id means 'any clinician'.
CREATE TABLE waiting_list_entries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
patient_id bigint NOT NULL REFERENCES patients (id),
clinician_id bigint REFERENCES clinicians (id),
earliest_date date NOT NULL,
latest_date date NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (latest_date >= earliest_date)
);Run the migrations and prove the rule
A runner needs to do four things: make sure schema_migrations exists, find which files have not run, run each one in order and write down that it ran. If a file fails halfway, it must undo that file completely. That is what the transaction is for.
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import type { Db } from "./db";
// A Db that can also run a whole file of statements (a pg Pool and PGlite both can).
export interface MigrationDb extends Db {
exec(sql: string): Promise<unknown>;
}
export async function migrate(db: MigrationDb, dir: string): Promise<string[]> {
await db.exec(
"CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())",
);
const done = await db.query<{ version: string }>("SELECT version FROM schema_migrations");
const applied = new Set(done.rows.map((row) => row.version));
const files = (await readdir(dir)).filter((name) => name.endsWith(".sql")).sort();
const newlyApplied: string[] = [];
for (const file of files) {
if (applied.has(file)) continue;
const sql = await readFile(join(dir, file), "utf8");
await db.exec("BEGIN");
try {
await db.exec(sql);
await db.query("INSERT INTO schema_migrations (version) VALUES ($1)", [file]);
await db.exec("COMMIT");
} catch (error) {
await db.exec("ROLLBACK");
throw error;
}
newlyApplied.push(file);
}
return newlyApplied;
}A small runner. A pg Pool and PGlite, an in-memory PostgreSQL that is handy for tests, both offer query and exec.
MigrationDbis the small database interface from Module 3, plusexec, which runs a whole file of statements.- The
schema_migrationstable is created if missing, then read to learn which versions have run. - Files are sorted by name, so the numbers decide the order. That is why names start with 001, 002, 003.
BEGINandCOMMITwrap each file together with its tick in schema_migrations. On any error,ROLLBACKundoes the file, and the error is thrown again so you see it.
const fresh = new PGlite();
console.log("first run :", await migrate(fresh, MIGRATIONS_DIR));
console.log("second run:", await migrate(fresh, MIGRATIONS_DIR));first run : [
'001_core_tables.sql',
'002_bookings_and_changes.sql',
'003_waiting_list.sql'
]
second run: []The first run applies all three files. The second run finds nothing to do, which is the point of the tick-list. Now the important test: try to break NFR-01. Patient A books slot 2. Then Patient B tries to book the same slot.
const book = "INSERT INTO bookings (slot_id, patient_id, status) VALUES ($1, $2, 'booked')";
await db.query(book, [2, 1]);
try {
await db.query(book, [2, 2]);
} catch (error) {
const e = error as { code?: string; constraint?: string; message: string };
console.log("double booking:", e.code, "|", e.constraint, "|", e.message);
}double booking: 23505 | one_live_booking_per_slot | duplicate key value violates unique constraint "one_live_booking_per_slot"The error code 23505 is PostgreSQL's code for 'unique violation'. The constraint field names the rule that was broken: one_live_booking_per_slot. Later in this module, the server turns this exact error into a polite 409 response.
A good rule must also allow what is allowed. After a cancellation the slot should be free again, and the CHECK rules should block nonsense values.
await db.query("UPDATE bookings SET status = 'cancelled' WHERE slot_id = 2");
await db.query(book, [2, 2]);
console.log("after cancelling, slot 2 can be booked again");
try {
await db.query("INSERT INTO slots (clinician_id, starts_at, ends_at) VALUES (1, '2026-12-05T09:00:00Z', '2026-12-05T08:00:00Z')");
} catch (error) {
console.log("bad slot:", (error as { code?: string }).code, "|", (error as Error).message);
}
try {
await db.query("INSERT INTO bookings (slot_id, patient_id, status) VALUES (3, 1, 'maybe')");
} catch (error) {
console.log("bad status:", (error as { code?: string }).code, "|", (error as Error).message);
}after cancelling, slot 2 can be booked again
bad slot: 23514 | new row for relation "slots" violates check constraint "slots_check"
bad status: 23514 | new row for relation "bookings" violates check constraint "bookings_status_check"PostgreSQL gave the unnamed CHECK rules automatic names, slots_check and bookings_status_check. If you want clearer messages, name your constraints yourself.
Review generated SQL before you apply it
An assistant can write migrations in seconds. It can also write ones that run without any error and still break a rule. SQL that runs is not SQL that is right. Read every line against the model, using this checklist.
| Check | What to look for | Tidewell example |
|---|---|---|
| Every table has a primary key | An id column that is unique and never empty. | All six tables use an identity id. |
| Required columns are NOT NULL | Optional columns are optional on purpose. | phone may be empty. email may not. |
| Links are foreign keys | Each id column points at a real table. | bookings.slot_id references slots. |
| Allowed values are checked | Status and role columns have a CHECK list. | status is 'booked' or 'cancelled'. |
| Uniqueness matches the rule | Neither too loose nor too strict. | One live booking, not one booking ever. |
| Types fit the data | Moments in time use timestamptz. | starts_at is timestamptz. |
| Nothing destructive | No DROP, TRUNCATE or DELETE without a clear reason. | A new-table migration has no DROP. |
| Only needed personal data | Columns match CON-01. | No date of birth, no notes. |
| Matches the model | No extra tables or columns. | No payments table. |
A mistake that runs without errors
A common draft puts a plain UNIQUE on the slot column. It looks right: one booking per slot. The test below shows what really happens after a cancellation.
// What a rushed draft might contain: a plain UNIQUE on slot_id.
await db.exec(`
CREATE TABLE draft_bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slot_id bigint NOT NULL UNIQUE REFERENCES slots (id),
status text NOT NULL
)`);
await db.query("INSERT INTO draft_bookings (slot_id, status) VALUES (2, 'booked')");
await db.query("UPDATE draft_bookings SET status = 'cancelled' WHERE slot_id = 2");
try {
await db.query("INSERT INTO draft_bookings (slot_id, status) VALUES (2, 'booked')");
} catch (error) {
console.log("draft design, rebooking after a cancel:", (error as Error).message);
}draft design, rebooking after a cancel: duplicate key value violates unique constraint "draft_bookings_slot_id_key"The cancelled row still holds the slot, so nobody can book it again. The partial unique index from migration 002 avoids this. Only a test that tries the awkward case, here 'cancel and rebook', finds this kind of bug.
Step-by-step workflow
Step 1: Start from the reviewed model
Open your data model and trace table. Do not ask for SQL until the model is confirmed.
What you should see: A model where every table has a requirement ID.
Step 2: Ask the assistant for a draft migration
Use the prompt card. Ask for one numbered file at a time, in the order the tables depend on each other.
What you should see: One draft file, such as 001_core_tables.sql.
Step 3: Read it against the checklist
Go through the review table line by line. Fix or remove what does not match the model.
What you should see: A reviewed file with a note of every change.
Step 4: Run it on a throwaway database
Apply it to an empty local database, never to the live one. A real PostgreSQL engine, or PGlite in tests, both work.
What you should see: The runner lists the file as applied.
Step 5: Break each important rule on purpose
For every rule that matters, write a small test that tries to break it and another that proves the allowed case still works.
What you should see: Real error messages, and a passing allowed case.
Step 6: Commit, and never edit it again
Commit the file with its number. If you find a mistake later, add a new file that fixes it.
What you should see: A history of numbered files that rebuilds the database.
- Reviewed model
Trace table
- Assistant draft
One file at a time
- Checklist review
Read every line
- Throwaway database
Run it
- Break the rules
Read the errors
- Commit
Numbered, then frozen
Each file is read before it is run, and tested before it is trusted.
Assistants and SQL: where the lines are
| Task | Assistant's part | Your part |
|---|---|---|
| Draft a migration | Writes the CREATE TABLE statements from your model. | Review every line with the checklist. |
| Explain a statement | Describes in plain words what a line does. | Check the explanation against the PostgreSQL docs. |
| Suggest tests | Proposes cases that break each rule. | Run them and read the real error messages. |
| Spot risks | Flags locks, missing indexes and destructive statements. | Decide what is worth fixing now. |
| Apply the migration | Nothing. It should never run SQL on live data. | You run it, on a throwaway database first. |
Conclusion and your next step
A schema is the blueprint, and migrations are the numbered log that builds it. Never edit an applied file. Run migrations in order, prove each important rule by breaking it on purpose, and read every line of generated SQL before it runs.
Your next step: write your capstone's first migration, run it on a throwaway database and trigger one rule on purpose. Then continue to Designing an API Contract, where you describe how the outside world will talk to this data.
For a longer practice project, see the Appointment Booking Portal. To check generated code in general, use the AI-Generated Code Review Checklist.
Reusable prompt
Migration draft and safety review
Asks for one migration file drafted from a confirmed model, with a list of risks and tests, and no changes to the model.
You are helping me write a PostgreSQL migration. Do not change the model, add tables or add columns that I did not list.
Fictional clinic: Tidewell Physiotherapy. Personal data must stay minimal.
Model for this file (migration 002_bookings_and_changes.sql):
- bookings: id (identity, primary key), slot_id (required, references slots), patient_id (required, references patients), status (required, 'booked' or 'cancelled'), created_at (required, default now), cancelled_at (optional).
- Rule NFR-01: at most one live booking per slot. Cancelled bookings must not block a new booking.
- booking_changes: id, booking_id (required, references bookings), action ('created', 'moved', 'cancelled'), actor_role ('patient' or 'staff'), actor_id (required), from_slot_id and to_slot_id (both optional, reference slots), changed_at (required, default now). Rows are only ever added.
Tasks:
1. Write the SQL for this one file. Use snake_case names and timestamptz for moments in time.
2. After the SQL, list any statement that could lose data or lock a large table.
3. List five tests that try to break the rules, each with the error you expect.
4. List anything you were unsure about as questions. Do not guess.Show the reusable template
Replace each {{placeholder}} with your own details.
You are helping me write a PostgreSQL migration. Do not change the model, add tables or add columns that I did not list.
Context: {{organisation_and_data_rules}}.
Model for this file ({{migration_file_name}}):
{{tables_columns_and_rules}}
Tasks:
1. Write the SQL for this one file. Use snake_case names and timestamptz for moments in time.
2. After the SQL, list any statement that could lose data or lock a large table.
3. List five tests that try to break the rules, each with the error you expect.
4. List anything you were unsure about as questions. Do not guess.Expected output and limitations
One SQL file that matches your model, a short list of risks, five break-the-rule tests with expected errors and a list of open questions.
-- 002_bookings_and_changes.sql
CREATE TABLE bookings ( ... );
CREATE UNIQUE INDEX one_live_booking_per_slot ON bookings (slot_id) WHERE status = 'booked';
CREATE TABLE booking_changes ( ... );
Risks
None here: both tables are new, so nothing is locked or lost.
Tests
1. Two live bookings for one slot -> unique violation.
2. Status 'maybe' -> check violation.
3. Booking for a slot id that does not exist -> foreign key violation.
4. Cancel, then book the same slot again -> allowed.
5. A change row with actor_role 'admin' -> check violation.
Questions
Should a booking ever be deleted, or only cancelled?Limitations to keep in mind
- The SQL may look right and still miss a rule. Run the tests yourself and read the real errors.
- The expected errors are guesses. Exact messages and constraint names depend on your database.
- It may add columns such as a notes field. Remove anything the model does not list.
Common errors and how to fix them
An applied migration was edited to fix a mistake.
Why it happens: Editing felt faster than adding a file.
Fix: Restore the original text from version control, then add a new numbered migration that makes the fix.
A plain UNIQUE on the slot column blocks rebooking after a cancellation.
Why it happens: The rule 'one booking per slot' was read as 'one booking ever'.
Fix: Use a partial unique index that covers only live bookings, and test the cancel-and-rebook case.
The migration ran fine, but nothing tests the rules.
Why it happens: Success was taken to mean correctness.
Fix: Write one test per important rule that breaks it on purpose, and one that proves the allowed case still works.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
A first migration for Ferngate
Write a migration for Ferngate Cycle Repairs with parts, jobs and stock movements from your model. Ask an assistant for a draft, review it with the checklist, run it on a throwaway database and break one rule on purpose.
You will need
- Your Ferngate data model from the last lesson.
- Note: a part taken for a job reduces stock. A delivery from a supplier increases it.
- Note: the low-stock threshold is 'to be agreed', so it must not appear as a fixed number.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Decide first whether a movement stores a signed number or a quantity plus a direction. Pick one and write down why.
- To test a foreign key, insert a movement for a part id that does not exist.
Show a model answer
A strong answer has one file, with parts, jobs and stock_movements in dependency order. Parts and jobs come first, because movements point at both. It uses CHECK rules for the quantity and the reason, keeps the threshold out of the file or as an empty column, and shows a real error such as a foreign key violation or a check violation, copied exactly. The review note names something concrete, for example 'removed a supplier_orders table the model did not list' or 'changed timestamp to timestamptz'. The point is not the number of tables. It is that every line was read and one rule was proved by breaking it.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A new numbered file changes every copy of the database in the same way. Editing the old file is tempting because it is quick, but databases that already ran the old text never see the edit, so they drift apart.
Show the answer and explanation
Answer: B. The rule is about live bookings only, and the partial index counts only rows with status 'booked'. Speed is the tempting reason, but it is not the point. A plain UNIQUE is allowed, and it enforces the wrong rule.
Show the answer and explanation
Answer: A. Valid SQL only means PostgreSQL accepted it. A missing constraint raises no error at all. The tempting reading, 'no error means correct', is why each important rule needs a test that tries to break it.
Frequently asked questions
What is a database migration?
It is a numbered file that changes the structure of a database, such as adding a table or a column. Running the files in order builds the same database on every computer. It is like a renovation log for a building.
Why should I never edit a migration that has already run?
Other databases, such as a teammate's laptop or the live system, have already run the old version, and they will not run it again. If you edit the file, those databases and a new one no longer match. Add a new migration for the change.
Do I need a migration tool such as Prisma or Flyway?
You can start with plain SQL files and a short runner, as in this lesson. Tools add conveniences like automatic ordering and rollbacks. Choose one that fits your language and team, and keep migrations readable either way.
Is it safe to let AI write my SQL migrations?
It is safe if you treat the output as a draft. Read every line against your model, run it on a throwaway database and test the rules. Never run assistant SQL on live data without that review, and never paste real personal data into a prompt.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Constraints(opens in a new tab)
PostgreSQL Global Development Group · Official documentation · The official guide to CHECK, NOT NULL, UNIQUE and foreign key constraints.
- Partial Indexes(opens in a new tab)
PostgreSQL Global Development Group · Official documentation · Explains an index over only some rows, including the unique case used here.
- Evolutionary Database Design(opens in a new tab)
martinfowler.com · Why databases change in small, scripted steps, and how teams keep them in step.
- PGlite(opens in a new tab)
PGlite · Official documentation · The in-memory PostgreSQL used by the test examples in this module.
- SQL Injection Prevention Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Why queries use parameters instead of joined-up strings.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.