Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 2.3

Migrations you can run twice: checkpoint files

Git tag in the reference repository
lesson/m02-l03 (commit af48e24)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 7, pass 7, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m02-l03 -- src.

Files changed in this lesson

.env.example added

.env.example
# Copy this file to .env and adjust if needed. Never commit .env.DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker

package-lock.json changed

Generated by npm from package.json. Do not edit it by hand; run the npm commands from the lesson.

package.json changed

package.json
{  "name": "caretaker",  "version": "1.0.0",  "description": "",  "scripts": {    "test": "NODE_ENV=test node --test --test-reporter=spec",    "start": "node src/server.js",    "dev": "node --watch src/server.js",    "db:migrate": "node --env-file=.env scripts/migrate.js"  },  "keywords": [],  "author": "",  "license": "ISC",  "type": "module",  "dependencies": {    "ejs": "7.0.2",    "express": "5.3.0",    "pg": "8.23.1"  },  "devDependencies": {    "supertest": "7.3.2"  }}

scripts/migrate.js added

scripts/migrate.js
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);}

src/migrate.js added

src/migrate.js
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();  }}

Project tree at this checkpoint

.env.example
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
package-lock.json
package.json
public/css/style.css
scripts/migrate.js
src/app.js
src/migrate.js
src/server.js
test/issues.test.js
views/error.ejs
views/issues/index.ejs
views/issues/new.ejs
views/issues/show.ejs
views/not-found.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 2.3