Module 2 · Persistence and the relational data model
2.3 Migrations you can run twice
Install the pg driver, keep connection settings in .env, and write a small migration runner that records which SQL files have run, each inside a transaction.
Starting point
migrations/001_create_organisations_buildings_issues.sql exists and was applied by hand to the caretaker database. The caretaker_test database is still empty.
Outcome
caretaker/├── .env (ignored by Git)├── .env.example├── scripts/│ └── migrate.js└── src/ └── migrate.jsnpm run db:migrate applies every migration that has not run yet, records it in a schema_migrations table, and does nothing when everything is up to date. Running it twice is safe.
The problem
Applying SQL files by hand does not scale. Try to apply our file again:
docker compose exec -T db psql -U caretaker -d caretaker -v ON_ERROR_STOP=1 < migrations/001_create_organisations_buildings_issues.sql
ERROR: relation "organisations" already exists
PostgreSQL refuses: the table exists. To apply changes safely we must know which files have already run in each database: your development database, the test database, a teammate's laptop, a production server. A migration runner answers that by keeping a list inside the database itself.
Build it
1. Install the PostgreSQL driver
pg (also called node-postgres) is the standard PostgreSQL client for Node.js. It opens connections, sends SQL with parameters, and converts results into JavaScript objects.
npm install pg@8.23.1
added 14 packages, and audited 101 packages in 4s
35 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
2. Connection settings in .env
The runner needs to know where the database is. We describe it with a connection URL:
postgres://USER:PASSWORD@HOST:PORT/DATABASEpostgres://caretaker:caretaker_dev_password@localhost:5433/caretakerCreate .env.example. It documents the variables and is committed:
# Copy this file to .env and adjust if needed. Never commit .env.DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretakerThen create your own .env from it. .gitignore already excludes .env (lesson 1.1):
cp .env.example .env
Node loads this file when we pass --env-file=.env. Every line becomes a process.env entry before our code runs.
3. The runner, as a reusable function
Create src/migrate.js. It lives in src because our tests will call it too (lesson 2.6):
import fs from 'node:fs/promises';import path from 'node:path';import pg from 'pg'; const MIGRATIONS_DIR = path.join(import.meta.dirname, '..', 'migrations'); export async function migrate(databaseUrl, { log = console.log } = {}) { const client = new pg.Client({ connectionString: databaseUrl }); await client.connect(); try { await client.query(` CREATE TABLE IF NOT EXISTS schema_migrations ( name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() ) `); const { rows } = await client.query('SELECT name FROM schema_migrations'); const applied = new Set(rows.map((row) => row.name)); const files = (await fs.readdir(MIGRATIONS_DIR)).filter((f) => f.endsWith('.sql')).sort(); for (const file of files) { if (applied.has(file)) continue; const sql = await fs.readFile(path.join(MIGRATIONS_DIR, file), 'utf8'); await client.query('BEGIN'); try { await client.query(sql); await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [file]); await client.query('COMMIT'); log(`applied ${file}`); } catch (err) { await client.query('ROLLBACK'); throw new Error(`Migration ${file} failed: ${err.message}`); } } log('migrations are up to date'); } finally { await client.end(); }}Walk through it:
new pg.Client({ connectionString })describes one connection.connect()opens it;end()closes it in thefinallyblock, so the connection closes even if a migration fails.CREATE TABLE IF NOT EXISTS schema_migrationsis the runner's memory: one row per applied file.- We read the folder, keep
.sqlfiles, and sort them. That is why the file names start with001_,002_and so on. - Each pending file runs between
BEGINandCOMMIT. PostgreSQL can roll back table creation, so a migration that fails halfway leaves no partial changes, and its name is not recorded. Fix the file and run again. INSERT ... VALUES ($1)with[file]is our first parameterized query.$1is a placeholder;pgsends the value separately from the SQL text. Lesson 2.6 explains why that matters so much.
4. A command-line entry point
Create scripts/migrate.js, which reads the URL from the environment and calls the function:
import { migrate } from '../src/migrate.js'; const databaseUrl = process.env.DATABASE_URL;if (!databaseUrl) { console.error('DATABASE_URL is not set. Copy .env.example to .env, or pass --env-file.'); process.exit(1);} try { await migrate(databaseUrl);} catch (err) { console.error(err.message); process.exit(1);}await at the top level works because the file is an ES module. If DATABASE_URL is missing we stop with a clear message instead of letting pg guess a default.
Add a script for it:
npm pkg set scripts.db:migrate="node --env-file=.env scripts/migrate.js"
Run and inspect
Run it against the database you changed by hand:
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
Migration 001_create_organisations_buildings_issues.sql failed: relation "organisations" already exists
Reveal Why it failed, and why that is fine
The runner does not know about the tables you created by hand, so it tries to create them and PostgreSQL refuses. The migration ran in a transaction, so nothing changed. Hand-made changes are exactly what migrations prevent; from now on every schema change goes through a migration file.
Start from a clean development database. down -v deletes the volume, and with it all data; only do this to a local learning database:
docker compose down -v
Container caretaker-db-1 Stopping
Container caretaker-db-1 Stopped
Container caretaker-db-1 Removing
Container caretaker-db-1 Removed
Network caretaker_default Removing
Volume caretaker_pgdata Removing
Volume caretaker_pgdata Removed
Network caretaker_default Removed
docker compose up -d --wait
Network caretaker_default Creating
Network caretaker_default Creating
Volume caretaker_pgdata Creating
Volume caretaker_pgdata Creating
Volume caretaker_pgdata Created
Volume caretaker_pgdata Created
Network caretaker_default Created
Network caretaker_default Created
Container caretaker-db-1 Creating
Container caretaker-db-1 Created
Container caretaker-db-1 Starting
Container caretaker-db-1 Started
Container caretaker-db-1 Waiting
Container caretaker-db-1 Healthy
Now migrate:
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 001_create_organisations_buildings_issues.sql
migrations are up to date
And again:
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
migrations are up to date
Nothing applied the second time. Look at the runner's memory:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT name, applied_at FROM schema_migrations;\dt
name | applied_at
-----------------------------------------------+-------------------------------
001_create_organisations_buildings_issues.sql | 2026-11-28 14:39:32.110048+00
(1 row)
List of tables
Schema | Name | Type | Owner
--------+-------------------+-------+-----------
public | buildings | table | caretaker
public | issues | table | caretaker
public | organisations | table | caretaker
public | schema_migrations | table | caretaker
(4 rows)Migrate the test database too. We override DATABASE_URL for one command; the variable on the command line wins over --env-file:
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_test npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 001_create_organisations_buildings_issues.sql
migrations are up to date
Experiment
What happens when a migration has an error halfway through? Create a broken second migration: the first statement is fine, the second refers to a table that does not exist.
CREATE TABLE will_it_stay (id integer);ALTER TABLE no_such_table ADD COLUMN x integer;will_it_stay exist?npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
Migration 002_broken_example.sql failed: relation "no_such_table" does not exist
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT to_regclass('will_it_stay') AS table_exists;SELECT name FROM schema_migrations ORDER BY name;
table_exists
--------------
(1 row)
name
-----------------------------------------------
001_create_organisations_buildings_issues.sql
(1 row)Reveal Answer
No. to_regclass returns empty (null) because the whole migration ran in one transaction and was rolled back. schema_migrations still lists only 001. A failed migration leaves the database exactly as it was.
Delete the broken file:
rm migrations/002_broken_example.sql
Checkpoint
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
migrations are up to date
git add -A
git commit -m "Add a migration runner"
[main 9130791] Add a migration runner
5 files changed, 207 insertions(+), 3 deletions(-)
create mode 100644 .env.example
create mode 100644 scripts/migrate.js
create mode 100644 src/migrate.js
git status should not list .env. If it does, check .gitignore.
Symptom Error: connect ECONNREFUSED 127.0.0.1:5433
The database container is not running, or uses a different port. Run docker compose ps.
Symptom password authentication failed for user "caretaker"
The password in .env does not match compose.yaml. If you changed the password in compose.yaml after the first start, the old one is still stored in the volume; recreate it with docker compose down -v.
Symptom DATABASE_URL is not set
You ran node scripts/migrate.js directly. Use npm run db:migrate, which passes --env-file=.env.
Recap and next step
A migration is a numbered SQL file. The runner applies pending files in order, each in a transaction, and records them in schema_migrations, so it is safe to run any number of times against any database. .env holds the connection URL; .env.example documents it.
Our tables are empty. Next we seed them with the Caretaker scenario and practise the SQL we will use to read it.
Open the checkpoint files for lesson 2.3 (separate page; only files from this lesson and earlier)