Generate a PostgreSQL Migration from a Schema Diff

Dan Lynch

Dan Lynch

lesson header image

Changing a projection leaves the schema alone. To change the schema itself, give pgpm diff a before and an after. This time, add an optional published_year column to library.books and leave the reporting view unchanged.

bash
cat > schema-v2.sql <<'SQL'
CREATE SCHEMA library;
CREATE SCHEMA reporting;

CREATE TABLE library.books (
  id integer PRIMARY KEY,
  title text NOT NULL,
  published_year integer
);

CREATE VIEW reporting.book_titles AS
  SELECT id, title FROM library.books;
SQL

pgpm diff ./packages/library ./schema-v2.sql \
  --emit-migration ./packages --pkg library-v2-migration \
  --emit-sql ./projections/library-v2.sql \
  --emit-bundle ./projections/library-v2.bundle.tar.gz --verify

The diff reports one added column on the books table. --verify applies the generated module on top of the original in a scratch database and compares that catalog with a fresh deployment of schema-v2.sql.

All three outputs describe the same migration:

OutputWhat's inside
packages/library-v2-migration/A pgpm plan with deploy, revert, and verify scripts
projections/library-v2.sqlThe forward SQL in plan order
projections/library-v2.bundle.tar.gzAn executable pgpm migration bundle with a content digest
bash
cat projections/library-v2.sql
tar -tzf projections/library-v2.bundle.tar.gz

Apply the generated module to the course database, which already has the original schema:

bash
pgpm deploy --database projections_demo # Select library-v2-migration when prompted
pgpm verify --database projections_demo # Select library-v2-migration when prompted

Or, if you're not running interactively (for example, as an agent):

bash
pgpm deploy --database projections_demo --package library-v2-migration --yes --no-tty
pgpm verify --database projections_demo --package library-v2-migration --no-tty
bash
psql -X -v ON_ERROR_STOP=1 -d projections_demo -c 'SELECT published_year FROM library.books;'

The query succeeds with zero rows. Revert the generated migration in this disposable database. Use --no-recursive to target only the migration package and leave the original module deployed:

bash
pgpm revert --database projections_demo --package library-v2-migration --no-recursive

Or, if you're not running interactively (for example, as an agent):

bash
pgpm revert --database projections_demo --package library-v2-migration --no-recursive --yes --no-tty
bash
psql -X -v ON_ERROR_STOP=1 -d projections_demo -c '\d library.books'

The table is back to id and title. In a real database, that revert would also remove any data written to published_year.

Previous Lesson