Bwf/ GuideFrançais
Bwf Guide

Add a column to the Journal

We’d like to give each article a short summary. There are already articles in the Journal, written before anyone thought to ask for a summary. Let’s add a column they can leave empty.

Find the existing schema

Open examples/canonical/Migrations/ in your workshop checkout. There’s a file called 007_journal_schema.sql. If you wondered where 001 went, take a look inside 007. It can build the schema for a fresh database and it also contains upgrade logic for earlier Journal installations.

Django migrations

Read a table definition

A migration contains ordinary PostgreSQL statements. For instance, the small table below gives an account an ID and requires an email. Try reading the declaration of articles in 007 the same way. Which fields must an author fill in, and which ones have defaults?

On a fresh database, Bwf runs the migration files in order. TypedSQL checks its queries against the schema those files produce.

CREATE TABLE accounts (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text NOT NULL UNIQUE
);

Write the next migration

In a workshop checkout where 007 is the latest migration, create 008_article_summary.sql beside it. Put the statement below in the file. Once it’s applied, the old articles will have a null summary. If you decide to require one later, give those rows a value before you add NOT NULL. Keep 007 as it was. A database that has already recorded it won’t run it again.

ALTER TABLE articles ADD COLUMN summary text;

Run it twice

Set DATABASE_URL to the database for your workshop. Run the two commands below from the checkout. You should find the new filename in bwf_migrations. Run them again. You’ll still see one entry for 008. Bwf runs the migration in a transaction and uses the ledger to tell which files it has already applied.

scripts/bwf migrate
psql "$DATABASE_URL" -c 'SELECT name FROM bwf_migrations ORDER BY name'

Try it in the Journal

Open the Journal chapter