Generate a PostgreSQL Migration from a Schema Diff
Dan Lynch
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.
bashcat > 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:
bashcat 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:
bashpgpm 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):
bashpgpm deploy --database projections_demo --package library-v2-migration --yes --no-tty pgpm verify --database projections_demo --package library-v2-migration --no-tty
bashpsql -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:
bashpgpm revert --database projections_demo --package library-v2-migration --no-recursive
Or, if you're not running interactively (for example, as an agent):
bashpgpm revert --database projections_demo --package library-v2-migration --no-recursive --yes --no-tty
bashpsql -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.

