Caretaker Express · PostgreSQL · Cedar

Module 2 · Persistence and the relational data model

2.4 Seed data and reading it with SQL

Load the Caretaker scenario with fixed IDs, fix the identity sequences, and practise the joins, filters and grouping our pages will need.

≈ 40 min 16 steps 112 lines of code Replay verified

Starting point

Both databases have the three tables and a schema_migrations row. The tables are empty.

Outcome

npm run db:seed replaces all data with the course scenario:

Organisation Buildings Issues
1 Liffey Estates 10 Dublin Offices, 20 Cork Apartments 101–104, plus 24 extra issues for paging
2 Harbour Lets 30 Galway Studios, 40 Limerick House 105 (building 30), 106 (building 40)

You can answer questions such as "which open issues belong to organisation 1?" with SQL, and you know why identity sequences need attention after inserting fixed IDs.

The problem

Every lesson from now on talks about specific records: "Alice opens issue 101", "building 20 belongs to organisation 1". Those IDs must be the same on your machine, in the tests, and in the screenshots. So we insert rows with explicit IDs, and we need a way to reset the data to that known state at any time.

Build it

1. The seed module

Like the migration runner, the seed logic is a function in src so that tests can reuse it. Create src/seed.js:

Create filesrc/seed.jsJavaScript
export const organisations = [  { id: 1, name: 'Liffey Estates' },  { id: 2, name: 'Harbour Lets' },]; export const buildings = [  { id: 10, organisationId: 1, name: 'Dublin Offices' },  { id: 20, organisationId: 1, name: 'Cork Apartments' },  { id: 30, organisationId: 2, name: 'Galway Studios' },  { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [  { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },  { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },  { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },  { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },  { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },  { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [  'Loose handrail on stairs',  'Bins not collected',  'Corridor light not working',  'Radiator cold in room 2',  'Window does not close fully',  'Loose floor tile at entrance',  'Toilet cistern keeps running',  'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() {  const priorities = ['low', 'medium', 'high', 'critical'];  const statuses = ['open', 'investigating', 'closed'];  const issues = [];  for (let i = 0; i < 24; i++) {    issues.push({      id: 107 + i,      buildingId: i % 2 === 0 ? 10 : 20,      title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,      priority: priorities[i % priorities.length],      status: statuses[i % statuses.length],      occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),      description: '',    });  }  return issues;} export const issues = [...namedIssues, ...fillerIssues()]; export async function seed(client) {  await client.query('BEGIN');  try {    await client.query('TRUNCATE issues, buildings, organisations RESTART IDENTITY CASCADE');    for (const o of organisations) {      await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);    }    for (const s of buildings) {      await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);    }    for (const e of issues) {      await client.query(        `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)         VALUES ($1, $2, $3, $4, $5, $6, $7)`,        [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],      );    }    await client.query('COMMIT');  } catch (err) {    await client.query('ROLLBACK');    throw err;  }}
  • The data is plain exported arrays, so tests can import them to know what to expect.
  • TRUNCATE ... RESTART IDENTITY CASCADE empties the tables in one statement. CASCADE also empties tables that reference them, so the order of the list does not matter.
  • Everything runs in one transaction: either the whole scenario is loaded, or nothing changes.
  • Every value goes through $1, $2, ... placeholders, never string concatenation.

2. The command

Create filescripts/seed.jsJavaScript
import pg from 'pg';import { seed } from '../src/seed.js'; const client = new pg.Client({ connectionString: process.env.DATABASE_URL });await client.connect();try {  await seed(client);  console.log('seeded the Caretaker scenario');} finally {  await client.end();}
Runcaretaker/
npm pkg set scripts.db:seed="node --env-file=.env scripts/seed.js"

Run and inspect

Run and comparecaretaker/
npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT id, organisation_id, name FROM buildings ORDER BY id;
 id | organisation_id |      name       
----+-----------------+-----------------
 10 |               1 | Dublin Offices
 20 |               1 | Cork Apartments
 30 |               2 | Galway Studios
 40 |               2 | Limerick House
(4 rows)

Now create a new organisation the way the app will, letting PostgreSQL choose the ID:

Predict What ID will PostgreSQL give the new organisation?
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
INSERT INTO organisations (name) VALUES ('Test Co') RETURNING id;
ERROR:  duplicate key value violates unique constraint "organisations_pkey"
DETAIL:  Key (id)=(1) already exists.
Reveal Why it failed

The identity column takes values from a sequence, a counter that only moves when PostgreSQL generates a value. We inserted IDs 1 and 2 ourselves, so the counter is still at its start and hands out 1, which already exists. The error code is 23505, unique violation.

3. Move the sequences past the seeded IDs

After inserting explicit IDs we must tell each sequence where to continue. Add this inside the transaction, just before COMMIT:

Editsrc/seed.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
    for (const table of ['organisations', 'buildings', 'issues']) {      await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);    }    await client.query('COMMIT');  } catch (err) {
Show the whole src/seed.js after this change
export const organisations = [  { id: 1, name: 'Liffey Estates' },  { id: 2, name: 'Harbour Lets' },]; export const buildings = [  { id: 10, organisationId: 1, name: 'Dublin Offices' },  { id: 20, organisationId: 1, name: 'Cork Apartments' },  { id: 30, organisationId: 2, name: 'Galway Studios' },  { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [  { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },  { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },  { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },  { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },  { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },  { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [  'Loose handrail on stairs',  'Bins not collected',  'Corridor light not working',  'Radiator cold in room 2',  'Window does not close fully',  'Loose floor tile at entrance',  'Toilet cistern keeps running',  'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() {  const priorities = ['low', 'medium', 'high', 'critical'];  const statuses = ['open', 'investigating', 'closed'];  const issues = [];  for (let i = 0; i < 24; i++) {    issues.push({      id: 107 + i,      buildingId: i % 2 === 0 ? 10 : 20,      title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,      priority: priorities[i % priorities.length],      status: statuses[i % statuses.length],      occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),      description: '',    });  }  return issues;} export const issues = [...namedIssues, ...fillerIssues()]; export async function seed(client) {  await client.query('BEGIN');  try {    await client.query('TRUNCATE issues, buildings, organisations RESTART IDENTITY CASCADE');    for (const o of organisations) {      await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);    }    for (const s of buildings) {      await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);    }    for (const e of issues) {      await client.query(        `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)         VALUES ($1, $2, $3, $4, $5, $6, $7)`,        [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],      );    }    for (const table of ['organisations', 'buildings', 'issues']) {      await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);    }    await client.query('COMMIT');  } catch (err) {    await client.query('ROLLBACK');    throw err;  }}
  • pg_get_serial_sequence('buildings', 'id') finds the sequence behind the column.
  • setval(sequence, n) sets its current value, so the next generated ID is n + 1.
  • The table name inside FROM ${table} is interpolated because SQL placeholders can only stand for values, not for table or column names. That is safe here only because table comes from our own fixed list, never from user input. Remember this rule; we meet it again when we add sorting.

Seed again, and retry the insert:

Run and comparecaretaker/
npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
INSERT INTO organisations (name) VALUES ('Test Co') RETURNING id;
 id 
----
  3
(1 row)

INSERT 0 1

ID 3. Re-seed to remove "Test Co" again; seeding is how we return to the known state:

Run and comparecaretaker/
npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario

SQL we will use

Issues with their building and organisation names, newest first. Two joins follow the foreign keys:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT e.id, e.title, e.status, s.name AS building, o.name AS organisationFROM issues eJOIN buildings s ON s.id = e.building_idJOIN organisations o ON o.id = s.organisation_idWHERE e.id BETWEEN 101 AND 106ORDER BY e.occurred_at DESC;
 id  |                  title                   |    status     |    building     |  organisation  
-----+------------------------------------------+---------------+-----------------+----------------
 106 | Car park barrier stuck open              | open          | Limerick House  | Harbour Lets
 105 | Boiler lost pressure in plant room       | open          | Galway Studios  | Harbour Lets
 104 | Water stain on the ceiling of flat 7     | investigating | Cork Apartments | Liffey Estates
 103 | Front door lock sticks at entrance 4     | open          | Cork Apartments | Liffey Estates
 102 | Dripping tap in the second-floor kitchen | closed        | Dublin Offices  | Liffey Estates
 101 | Lift stuck between floors 2 and 3        | open          | Dublin Offices  | Liffey Estates
(6 rows)

How many issues does each building have? GROUP BY collapses rows into one per group; count(*) counts each group. LEFT JOIN keeps buildings with no issues:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT s.id, s.name, count(e.id) AS issuesFROM buildings sLEFT JOIN issues e ON e.building_id = s.idGROUP BY s.id, s.nameORDER BY s.id;
 id |      name       | issues 
----+-----------------+--------
 10 | Dublin Offices  |     14
 20 | Cork Apartments |     14
 30 | Galway Studios  |      1
 40 | Limerick House  |      1
(4 rows)

Open issues in one organisation. Notice that "belongs to organisation 1" is not a column on issues; it is a path through buildings. Tenant isolation in Modules 5 and 8 depends on this join:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT e.id, e.title, e.building_idFROM issues eJOIN buildings s ON s.id = e.building_idWHERE s.organisation_id = 1 AND e.status = 'open'ORDER BY e.idLIMIT 5;
 id  |                title                 | building_id 
-----+--------------------------------------+-------------
 101 | Lift stuck between floors 2 and 3    |          10
 103 | Front door lock sticks at entrance 4 |          20
 107 | Loose handrail on stairs (#107)      |          10
 110 | Radiator cold in room 2 (#110)       |          20
 113 | Toilet cistern keeps running (#113)  |          10
(5 rows)

Experiment

Seed scripts must be repeatable. Run the seed twice in a row and check the totals.

Predict After two seeds in a row, how many issues are there: 30 or 60?
Run and comparecaretaker/
npm run db:seed && npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT count(*) FROM issues;
 count 
-------
    30
(1 row)
Reveal Answer
  1. TRUNCATE empties the tables first, so the seed always produces the same state. A seed that appends would double the data every time and make every test unpredictable.

Checkpoint

Run and comparecaretaker/
git add -A
git commit -m "Seed the Caretaker scenario"
[main 30ae74b] Seed the Caretaker scenario
 3 files changed, 93 insertions(+), 1 deletion(-)
 create mode 100644 scripts/seed.js
 create mode 100644 src/seed.js
Symptom relation "issues" does not exist

The database was not migrated. Run npm run db:migrate first.

Symptom connect ECONNREFUSED 127.0.0.1:5432 (port 5432, not 5433)

DATABASE_URL is not set, so pg fell back to its defaults. Run through npm run db:seed, which loads .env.

Recap and next step

The seed loads a fixed scenario inside one transaction, resets the identity sequences with setval, and can run any number of times. You practised joins, LEFT JOIN, GROUP BY, and an organisation-scoped query that walks from issues through buildings.

Next we connect the Express app to PostgreSQL and replace the in-memory array, starting with the pages that read.