Databases · Advanced · 30 min
Change the clinic schema safely with versioned SQL migrations
By Padding · Updated 26 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7 · dbmate 2.38.2
You will put the clinic database under dbmate 2.38 migrations, then split each patient's full name into given and family names with expand and contract, a lock timeout, a batched backfill and a NOT NULL that never holds a long lock.
On this page
So far every change to the clinic database has been an ALTER TABLE typed into psql. That works while one person owns one database. It stops working the day there are three copies (your laptop, staging and the live server) and nobody can say which changes each one has had. It also hides the real danger of a schema change on a live system: a one-line ALTER TABLE can queue behind a long report, and every booking request queues behind the ALTER.
In this part you put the schema under versioned migrations with dbmate, a single binary that runs plain SQL files in order and records each one in a schema_migrations table. Then you make a change that would be risky done the quick way: splitting patients.full_name into given_name and family_name while the booking app keeps running. You do it with expand and contract: add the new columns, keep both shapes in sync, backfill old rows in small batches, make the new column required without a long lock, and only drop the old column once no code reads it.
The commands use PostgreSQL 18.7 and dbmate 2.38.2. PostgreSQL 19.0 came out on 19 November 2026; the steps should carry over to it unchanged, but this part was checked on 18.7 only. If you are on Python and prefer migrations generated from models, /tutorials/manage-database-migrations-in-python-with-alembic covers Alembic. This part stays with SQL you write yourself.
Step 1 · Install dbmate and check the download
dbmate is one static binary with no runtime to install. The project publishes builds on GitHub, and the release page lists a SHA-256 digest for each file. Checking the digest before you install proves the file you received is the file the project published, which matters for a tool that will run with the power to drop your tables.
The binary is about 34 MB. If you pay for data by the gigabyte, download it once and copy it to your other servers with scp rather than fetching it on each one.
Work in a throwaway folder. dpkg --print-architecture prints amd64 or arm64, which matches the names of the release files:
tmp=$(mktemp -d)
cd "$tmp"
arch=$(dpkg --print-architecture)
curl -fsSLO "https://github.com/amacneil/dbmate/releases/download/v2.38.2/dbmate-linux-${arch}"
cat > SHA256SUMS <<'EOF'
4c6059e4e52558605d39e8c8075f3b15f96cac293043c0c71bb464d8950f235c dbmate-linux-amd64
5d70ac9a7d337daa79d3f9821cf8bab3fbcfc41b5167557d9e096b8a31a61743 dbmate-linux-arm64
EOF
sha256sum --check --ignore-missing SHA256SUMSOnly if sha256sum prints OK, install it and remove the folder:
sudo install -m 755 "dbmate-linux-${arch}" /usr/local/bin/dbmate
cd ~
rm -r "$tmp"
dbmate --versionA binary in /usr/local/bin gets no security updates from apt. Watch the releases page at github.com/amacneil/dbmate/releases, and to upgrade, repeat these commands with the new version number and the digests shown on that release's page. Never copy a digest from anywhere else.
Check it worked
sha256sum printed dbmate-linux-amd64: OK (or arm64), and dbmate --version prints dbmate version 2.38.2. If sha256sum says FAILED, delete the file and download it again; do not install it.
Step 2 · Give migrations their own role and connection
Migrations should not run as the postgres superuser. A superuser can do anything, including things no migration should, and running as postgres hides permission mistakes until the day you move to a managed database that has no superuser. Create a role that owns the clinic's tables and does nothing else. Part 6 keeps this role and its password as they are, and adds separate, smaller roles for the app itself; this one never serves app traffic.
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
CREATE ROLE clinic_owner LOGIN;
ALTER DATABASE clinic OWNER TO clinic_owner;
-- Hand every table in the public schema to clinic_owner.
-- Identity sequences and indexes follow their table.
DO $$
DECLARE
t regclass;
BEGIN
FOR t IN
SELECT c.oid::regclass
FROM pg_class AS c
WHERE c.relnamespace = 'public'::regnamespace
AND c.relkind IN ('r', 'p')
AND pg_get_userbyid(c.relowner) = 'postgres'
LOOP
EXECUTE format('ALTER TABLE %s OWNER TO clinic_owner', t);
END LOOP;
END
$$;
SQL
sudo -u postgres createdb -O clinic_owner clinic_scratchOwning the database also gives clinic_owner the right to create objects in the public schema, because since PostgreSQL 15 that schema belongs to whoever owns the database. clinic_scratch is an empty database you will rebuild from the migrations to prove they work before they touch clinic. If you created views or functions in earlier parts, change their owner too with ALTER VIEW ... OWNER TO or ALTER FUNCTION ... OWNER TO.
dbmate reads the connection URL from a .env file in the folder you run it from. The role needs a password, and the password must not end up in your shell history or on a command line where other users can see it in the process list. The next commands generate a random one in a variable, set it by sending SQL to psql on standard input, and write it to a .env file that only you can read. Run them in one go; the ( ) keeps the variable and the strict umask inside a subshell.
Before you run them, check that sudo -u postgres psql -Atc 'SHOW log_statement;' prints none, the default. If it prints ddl or all, the server log would record the ALTER ROLE with the password in it; set the password with psql's \password clinic_owner instead and write it into .env by hand.
mkdir -p ~/clinic-demo
cd ~/clinic-demo
(
umask 077
pw=$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')
printf "ALTER ROLE clinic_owner PASSWORD '%s';\n" "$pw" | sudo -u postgres psql -X -q -v ON_ERROR_STOP=1
printf 'DATABASE_URL="postgres://clinic_owner:%s@127.0.0.1:5432/clinic?sslmode=disable"\n' "$pw" > .env
printf 'SCRATCH_DATABASE_URL="postgres://clinic_owner:%s@127.0.0.1:5432/clinic_scratch?sslmode=disable"\n' "$pw" >> .env
)
printf '.env\n' >> .gitignore
mkdir -p db/migrationsThe password is 48 hexadecimal characters, so it needs no escaping inside a URL. sslmode=disable is there because dbmate insists on TLS by default; the connection goes to 127.0.0.1 and never leaves the machine. For a database on another host, use sslmode=require or stricter. The .gitignore line keeps .env out of version control when you put this folder in Git.
Check it worked
ls -l .env
dbmate status
dbmate -e SCRATCH_DATABASE_URL status
sudo -u postgres psql -d clinic -c '\dt'ls shows -rw-------, so only you can read the file. Both dbmate status commands connect and print Applied: 0 and Pending: 0: there are no migration files yet. The \dt listing shows every clinic table with clinic_owner in the Owner column. If dbmate prints password authentication failed, the two printf lines did not see the same password; run the whole block again.
Step 3 · Turn the current schema into the baseline migration
The schema.sql you wrote in part 1 no longer describes the database: parts 2 and 4 changed it with ALTER TABLE and CREATE INDEX. The only accurate description is the database itself, so the first migration, the baseline, is a schema-only dump of clinic as it stands today.
dbmate new creates an empty migration whose name starts with the current UTC time, such as 20261126101500_baseline.sql. That number is the migration's version, and dbmate runs files in version order.
cd ~/clinic-demo
dbmate new baseline
f=$(ls db/migrations/*_baseline.sql)
{
echo '-- migrate:up'
sudo -u postgres pg_dump --schema-only --no-owner --no-privileges clinic \
| grep -v -E '^(SET |SELECT pg_catalog\.set_config|\\restrict |\\unrestrict )'
echo
echo '-- migrate:down'
echo "DO \$\$ BEGIN RAISE EXCEPTION 'The baseline cannot be rolled back. Restore a backup instead.'; END \$\$;"
} > "$f"
grep -c '^CREATE TABLE' "$f"The grep -v removes lines that only make sense when psql restores a dump. \restrict and \unrestrict are psql commands that dbmate cannot run. The SET lines and the set_config call change settings for the whole connection, including emptying the search_path, and that would break every later migration dbmate runs on the same connection. --no-owner and --no-privileges keep owners and grants out, so the same file builds the schema for whichever role runs it; part 6 adds grants as migrations of their own.
The down section refuses on purpose. Undoing the baseline would mean dropping every table, and that should never be one command away.
The clinic database already has this schema, so dbmate must not run the baseline there. Record it as applied instead. The schema_migrations table below is the one dbmate itself would create, and SET ROLE makes clinic_owner its owner:
v=$(basename "$f" | cut -d_ -f1)
sudo -u postgres psql -X -v ON_ERROR_STOP=1 -d clinic -v version="$v" <<'SQL'
SET ROLE clinic_owner;
CREATE TABLE IF NOT EXISTS public.schema_migrations (version varchar PRIMARY KEY);
INSERT INTO public.schema_migrations (version) VALUES (:'version');
SQL
dbmate statusNow prove the baseline really rebuilds the schema. Run it against the empty scratch database, then compare the two schemas:
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema migrate
diff <(sudo -u postgres pg_dump --schema-only --no-owner --no-privileges --restrict-key=compare clinic) \
<(sudo -u postgres pg_dump --schema-only --no-owner --no-privileges --restrict-key=compare clinic_scratch) \
&& echo "The schemas match"--no-dump-schema stops dbmate writing the scratch database's schema to db/schema.sql; that file should always describe clinic. The fixed --restrict-key makes both dumps print the same key line, so diff only reports real differences.
Check it worked
The grep -c printed 7, one per table. dbmate status lists [X] 2026..._baseline.sql with Applied: 1 and Pending: 0. The scratch run printed Applying: and Applied: for the baseline, and the last command printed The schemas match with no diff output above it. A difference means something in clinic was not captured, such as a database-level setting; settings like ALTER DATABASE clinic SET timezone from part 3 are not part of a schema dump and stay where they are.
Step 4 · Write a migration with up and down, and roll it back
The booking app is going to send SMS reminders and needs to remember which appointments already had one. That is a small, safe change: a nullable column with no default. PostgreSQL records it in the catalogue without rewriting the table, so it takes a moment even on the millions of appointments from part 3.
cd ~/clinic-demo
dbmate new add_appointment_reminder_sent_at
f=$(ls db/migrations/*_add_appointment_reminder_sent_at.sql)
cat > "$f" <<'SQL'
-- migrate:up
SET LOCAL lock_timeout = '3s';
ALTER TABLE appointments ADD COLUMN reminder_sent_at timestamptz;
-- migrate:down
SET LOCAL lock_timeout = '3s';
ALTER TABLE appointments DROP COLUMN reminder_sent_at;
SQLThe up section makes the change and the down section undoes it. dbmate runs each migration inside one transaction, so if any statement fails, nothing in that file is applied and its version is not recorded. SET LOCAL lock_timeout lasts until the end of that transaction; the next step shows why every migration starts with it.
Rehearse on the scratch database first. Apply it, roll it back, and apply it again, which proves both sections work:
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema migrate
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema rollback
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema migrateThen apply it to clinic, and look at what dbmate records:
dbmate migrate
sudo -u postgres psql -d clinic -c 'SELECT version FROM schema_migrations ORDER BY version;'
tail -n 8 db/schema.sqldbmate migrate only applies pending migrations to an existing database. dbmate up does the same but first creates the database if it is missing, which this role is not allowed to do anyway. After each migrate or rollback on clinic, dbmate writes the full schema to db/schema.sql. Commit that file alongside the migrations: a reviewer sees the effect of a migration as a diff of the schema, not only the SQL that caused it.
Check it worked
The rehearsal printed Applying:, Rolling back: and Applying: again for the same file. On clinic, the schema_migrations query lists two versions, the baseline's and the new one. The end of db/schema.sql is an INSERT INTO public.schema_migrations listing the same two versions. Running \d appointments in psql shows the new reminder_sent_at column, of type timestamp with time zone.
Step 5 · Expand the patients table behind a lock timeout
The clinic wants to address patients by their given name in reminders ("Hello Ngozi") and sort lists by family name. Today there is only full_name. The quick way, renaming the column and adding another in one release, breaks every copy of the app that is still running the old code during the deploy. Expand and contract splits the change so that at every moment both the old and the new app work:
- Expand: add
given_nameandfamily_name, and keep them in sync withfull_namewhichever one a client writes. - Backfill: fill the new columns for existing patients, in small batches.
- Tighten: make
given_namerequired, without a long lock. - Switch: release the app that reads and writes the new columns.
- Contract: once no running code reads
full_name, drop it and the sync.
Steps 1 and 2 of that list happen here and in the next step.
Adding a column is quick, but it needs an ACCESS EXCLUSIVE lock on patients, and that lock has to wait for every transaction already using the table, even a plain SELECT. While it waits, every new query on patients queues behind it. A slow report holding the table for two minutes means two minutes of booking requests stuck, because of a change that takes a millisecond. lock_timeout makes the migration give up after three seconds instead, so the worst case is a failed migration you retry, not a stalled app.
The sync is a trigger. When a client writes only full_name (the old app), it fills the two new columns. When a client writes only the new columns (the new app), it rebuilds full_name. When a client writes both, it trusts the client.
The split rule takes everything before the first space as the given name and the rest as the family name. That is a guess, not a fact about the person. Many patients go by a single name, some families put the family name first, and a name like Mary Jane Okafor splits as Mary and Jane Okafor. So family_name stays optional, full_name stays the record of what the patient gave you until the contract step, and the new app should let patients and receptionists correct both parts.
cd ~/clinic-demo
dbmate new add_patient_name_parts
f=$(ls db/migrations/*_add_patient_name_parts.sql)
cat > "$f" <<'SQL'
-- migrate:up
SET LOCAL lock_timeout = '3s';
ALTER TABLE patients
ADD COLUMN given_name text,
ADD COLUMN family_name text;
CREATE FUNCTION patients_sync_names() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
full_changed boolean;
parts_changed boolean;
BEGIN
IF TG_OP = 'INSERT' THEN
full_changed := NEW.full_name IS NOT NULL AND NEW.given_name IS NULL;
parts_changed := NEW.given_name IS NOT NULL AND NEW.full_name IS NULL;
ELSE
full_changed := NEW.full_name IS DISTINCT FROM OLD.full_name
AND NEW.given_name IS NOT DISTINCT FROM OLD.given_name
AND NEW.family_name IS NOT DISTINCT FROM OLD.family_name;
parts_changed := NEW.full_name IS NOT DISTINCT FROM OLD.full_name
AND (NEW.given_name IS DISTINCT FROM OLD.given_name
OR NEW.family_name IS DISTINCT FROM OLD.family_name);
END IF;
IF full_changed THEN
NEW.given_name := split_part(NEW.full_name, ' ', 1);
NEW.family_name := CASE WHEN strpos(NEW.full_name, ' ') > 0
THEN substr(NEW.full_name, strpos(NEW.full_name, ' ') + 1)
END;
ELSIF parts_changed THEN
NEW.full_name := concat_ws(' ', NEW.given_name, NEW.family_name);
END IF;
RETURN NEW;
END
$$;
CREATE TRIGGER patients_sync_names
BEFORE INSERT OR UPDATE ON patients
FOR EACH ROW EXECUTE FUNCTION patients_sync_names();
-- migrate:down
SET LOCAL lock_timeout = '3s';
DROP TRIGGER patients_sync_names ON patients;
DROP FUNCTION patients_sync_names();
ALTER TABLE patients DROP COLUMN given_name, DROP COLUMN family_name;
SQL
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema migrateThe rehearsal on the scratch database applies at once, because nothing else is using it. Now see what happens on a busy table. In a second terminal, open psql on clinic and start a transaction that reads patients and stays open, as a long report would:
sudo -u postgres psql -d clinicBEGIN;
SELECT count(*) FROM patients;Leave it there. Back in the first terminal, apply the migration to clinic:
dbmate migrateAfter three seconds it fails with something like Error: pq: canceling statement due to lock timeout. Nothing was applied. Confirm it is still pending:
dbmate statusNow end the transaction in the second terminal by typing COMMIT;, and quit that psql with \q. Then run the migration again in the first terminal:
dbmate migrateIn a deploy script, wrap dbmate migrate in a short retry loop (three tries, a few seconds apart) rather than raising the timeout. If it keeps failing, find the blocker in pg_stat_activity before trying again.
Check it worked
The second dbmate migrate prints Applying: and Applied: for add_patient_name_parts.sql. Now write patients the way each version of the app will. The first two rows come from the old app, which only knows full_name; the third from the new app, which only knows the parts:
sudo -u postgres psql -v ON_ERROR_STOP=1 -d clinic <<'SQL'
INSERT INTO patients (full_name, email, phone) VALUES
('Zainab', 'zainab.migration@example.org', '+2348030000101'),
('Mary Jane Okafor', 'maryjane.migration@example.org', '+2348030000102');
INSERT INTO patients (given_name, family_name, email, phone) VALUES
('Chiamaka', 'Nwosu', 'chiamaka.migration@example.org', '+2348030000103');
SELECT full_name, given_name, family_name
FROM patients
WHERE email LIKE '%.migration@example.org'
ORDER BY email;
SQLThe query returns three rows: Chiamaka Nwosu split as Chiamaka and Nwosu (its full_name built by the trigger), Mary Jane Okafor as Mary and Jane Okafor, and Zainab with an empty family_name. Existing patients still have empty new columns; the next step fills them.
Step 6 · Backfill the new columns in batches
One UPDATE patients SET given_name = ... over 200,000 rows would work, but it holds row locks on every patient until it commits, writes a new version of every row at once, and if it fails near the end it throws all of it away. Batches keep each transaction short: a booking that touches a patient waits for one batch at most, and a failure loses one batch, not the lot.
A backfill is a data change, not a schema change, so it lives in its own script rather than in a migration. It can run for minutes on a large table, and it must commit between batches, which a single migration transaction cannot do. A DO block run on its own by psql can COMMIT inside its loop. The script walks the table in ranges of id, which uses the primary key index, and only touches rows that are still empty, so you can stop it and run it again safely.
cd ~/clinic-demo
cat > backfill-patient-names.sql <<'SQL'
\set ON_ERROR_STOP on
DO $$
DECLARE
batch_size constant bigint := 10000;
last_id bigint := 0;
max_id bigint;
BEGIN
SELECT coalesce(max(id), 0) INTO max_id FROM patients;
WHILE last_id < max_id LOOP
UPDATE patients
SET given_name = split_part(full_name, ' ', 1),
family_name = CASE WHEN strpos(full_name, ' ') > 0
THEN substr(full_name, strpos(full_name, ' ') + 1)
END
WHERE id > last_id
AND id <= last_id + batch_size
AND given_name IS NULL;
last_id := last_id + batch_size;
COMMIT;
RAISE NOTICE 'backfilled patients up to id %', last_id;
PERFORM pg_sleep(0.2);
END LOOP;
END
$$;
SELECT count(*) FILTER (WHERE given_name IS NULL) AS still_empty,
count(*) AS patients
FROM patients;
SQL
sudo -u postgres psql -d clinic < backfill-patient-names.sqlThe short pg_sleep between batches gives autovacuum, replicas and the app room to keep up. Rows inserted while the script runs do not need it: the trigger fills them. Because the trigger also runs on each backfilled row, it rebuilds full_name from the two parts, which gives back exactly the original text, so the column is unchanged.
Check it worked
psql prints one NOTICE: backfilled patients up to id ... line per batch, then still_empty as 0 next to your patient count. Spot-check that the two shapes agree everywhere:
sudo -u postgres psql -d clinic -c "SELECT count(*) AS out_of_sync FROM patients WHERE full_name IS DISTINCT FROM concat_ws(' ', given_name, family_name);"It prints 0. Any other number means some rows were written in a way the trigger does not cover; look at a few with the same WHERE clause before going further.
Step 7 · Make given_name required without a long lock
Every patient now has a given_name, and the trigger fills it for new ones. Make the database guarantee it. A plain ALTER COLUMN given_name SET NOT NULL scans the whole table to check for NULLs while holding ACCESS EXCLUSIVE, so no one can read or write patients for the length of the scan. Two migrations avoid that:
- The first adds a
CHECK (given_name IS NOT NULL)markedNOT VALID. It applies to new and changed rows at once, and skips checking the old ones, so it needs the strong lock only for an instant. - The second runs
VALIDATE CONSTRAINT, which scans the table under aSHARE UPDATE EXCLUSIVElock that lets reads and writes carry on. ThenSET NOT NULLsees a valid check that already proves there are no NULLs and skips its own scan, so its strong lock is brief too. The check is then redundant and is dropped.
They are separate files so that each runs in its own transaction, and the first commits before the long scan begins.
cd ~/clinic-demo
dbmate new require_patient_given_name
f=$(ls db/migrations/*_require_patient_given_name.sql)
cat > "$f" <<'SQL'
-- migrate:up
SET LOCAL lock_timeout = '3s';
ALTER TABLE patients
ADD CONSTRAINT patients_given_name_present CHECK (given_name IS NOT NULL) NOT VALID;
-- migrate:down
SET LOCAL lock_timeout = '3s';
ALTER TABLE patients DROP CONSTRAINT patients_given_name_present;
SQLdbmate new set_patient_given_name_not_null
f=$(ls db/migrations/*_set_patient_given_name_not_null.sql)
cat > "$f" <<'SQL'
-- migrate:up
SET LOCAL lock_timeout = '3s';
ALTER TABLE patients VALIDATE CONSTRAINT patients_given_name_present;
ALTER TABLE patients ALTER COLUMN given_name SET NOT NULL;
ALTER TABLE patients DROP CONSTRAINT patients_given_name_present;
-- migrate:down
SET LOCAL lock_timeout = '3s';
ALTER TABLE patients ALTER COLUMN given_name DROP NOT NULL;
ALTER TABLE patients
ADD CONSTRAINT patients_given_name_present CHECK (given_name IS NOT NULL) NOT VALID;
SQL
dbmate -e SCRATCH_DATABASE_URL --no-dump-schema migrate
dbmate migratePostgreSQL 18 can also add a not-null constraint itself as NOT VALID (ADD CONSTRAINT ... NOT NULL given_name NOT VALID, then VALIDATE CONSTRAINT), which saves the extra check. The CHECK route above works the same on PostgreSQL 12 and later, which helps if your staging and live servers are on different major versions.
Check it worked
Each dbmate migrate applies both new files, one after the other. sudo -u postgres psql -d clinic -c '\d patients' shows not null against given_name and nothing against family_name, and patients_given_name_present is gone from the constraints. Now try to blank a given name:
sudo -u postgres psql -d clinic -c "UPDATE patients SET given_name = NULL WHERE email = 'zainab.migration@example.org';"PostgreSQL refuses with something like null value in column "given_name" of relation "patients" violates not-null constraint, and the row is unchanged.
Step 8 · Switch the app, then rehearse the contract
The switch happens in the app, not the database. Release the version that reads given_name and family_name and writes them (it may still write full_name too; the trigger copes with either). While old and new copies run side by side during the deploy, the trigger keeps both shapes in step, which is the point of the expand phase.
Only when no running code reads full_name (every app server, every background worker, every report and export) is it safe to contract. That is usually a later release, days or weeks on. Write the contract migration now, keep it out of db/migrations so nobody applies it early, and rehearse it on the scratch database:
cd ~/clinic-demo
mkdir -p db/contract
cat > db/contract/drop_patient_full_name.sql <<'SQL'
-- migrate:up
SET LOCAL lock_timeout = '3s';
DROP TRIGGER patients_sync_names ON patients;
DROP FUNCTION patients_sync_names();
ALTER TABLE patients DROP COLUMN full_name;
-- migrate:down
DO $$ BEGIN RAISE EXCEPTION 'Dropping full_name is one-way. Restore a backup to undo it.'; END $$;
SQLThe down section refuses, like the baseline's. Once full_name is gone, a down that re-adds an empty column would only pretend to undo the change. The safety net for a contract step is the weeks of expand phase before it and a tested backup, which part 7 sets up.
To rehearse, copy the applied migrations and the contract into a separate folder, giving the contract a version the way dbmate new would, and point dbmate at that folder with -d:
mkdir -p db/rehearsal
cp db/migrations/*.sql db/rehearsal/
cp db/contract/drop_patient_full_name.sql "db/rehearsal/$(date -u +%Y%m%d%H%M%S)_drop_patient_full_name.sql"
dbmate -e SCRATCH_DATABASE_URL -d db/rehearsal --no-dump-schema migrate
sudo -u postgres psql -d clinic_scratch -Atc "SELECT string_agg(column_name, ', ' ORDER BY ordinal_position) FROM information_schema.columns WHERE table_name = 'patients';"When the day comes, run dbmate new drop_patient_full_name, paste in the contents of db/contract/drop_patient_full_name.sql, and apply it like any other migration.
In a deploy pipeline, dbmate status --exit-code is a useful gate: it exits with 1 when migrations are pending, so a release can refuse to start against a database that is behind. dbmate migrate --strict (or DBMATE_STRICT=true in the environment) refuses to apply a migration older than one already applied, which catches a long-lived branch merged out of order.
Check it worked
The rehearsal applies only the contract file, because the scratch database already has the others. The column list for clinic_scratch has given_name and family_name and no full_name. On clinic, nothing changed:
dbmate status --exit-code
sudo -u postgres psql -d clinic -Atc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'patients' AND column_name = 'full_name';"dbmate status lists five applied migrations, Pending: 0, and exits with 0. The second command prints 1: full_name is still there, as parts 6 to 8 expect. Remove the rehearsal folder and the scratch database; you can recreate the database at any time with createdb -O clinic_owner clinic_scratch and dbmate -e SCRATCH_DATABASE_URL migrate.
rm -r db/rehearsal
sudo -u postgres dropdb clinic_scratchKeep ~/clinic-demo with its .env, db/migrations, db/contract and db/schema.sql, the clinic_owner role and dbmate itself. Part 6 picks up clinic_owner as it is, reuses the password in .env rather than resetting it, and adds the app's roles beside it; part 8 removes the demo databases and roles at the end of the series.
Next steps
- Give the booking app its own login roles with only the access it needs, owned schema and all: /tutorials/give-the-clinic-app-least-privilege-database-roles
- Go back to the indexes this part's migrations sit alongside, including
CREATE INDEX CONCURRENTLY, which needs a dbmate migration markedtransaction:false: /tutorials/index-the-clinic-database-for-the-queries-it-really-runs - See why a waiting lock blocks the queries behind it, and how transactions see each other's changes: /tutorials/understand-postgresql-transactions-and-isolation-levels
- Do the same kind of versioned change from Python models with Alembic: /tutorials/manage-database-migrations-in-python-with-alembic
Related tutorials
- Use SQLite safely in a Python app: WAL mode, foreign keys and busy timeoutsYou will build a small room-booking store on SQLite with Python 3.15, reproduce the "database is locked" error with two writer processes, and end with a connection helper that turns on foreign keys, WAL mode, a busy timeout and BEGIN IMMEDIATE writes, plus a tested online backup.
- Throttle login attempts with a sliding window in RedisYou will protect a Python login function from password guessing with a sliding-window log in Redis sorted sets, checked atomically in a Lua script, with per-address lockouts that double each time, an account-wide rule that asks for an extra check instead of locking the owner out, and tests that replay 50 guesses.
- Run background jobs with Redis Streams and consumer groupsYou will build a small receipt-sending job queue on Redis 8 Streams with two Python workers that share the work, recover jobs from a crashed worker, park repeated failures in a dead-letter stream and never send the same receipt twice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials