Import a PostgreSQL Schema into a PGPM Module
Dan Lynch
A projection changes how pgpm represents a schema, not what the schema does. pgpm parses SQL into database objects, such as tables and views, and uses their identities and dependencies to generate different outputs. We'll follow one library schema from plain SQL to a module, then change how pgpm writes and organizes it.
Start a fresh workspace
You'll need Node.js 22 or later, the latest pgpm, Docker, and the PostgreSQL client tools (psql, pg_isready, and createdb). Run these commands from a directory that doesn't already contain projections-demo:
bashpgpm init workspace # Enter projections-demo when prompted cd projections-demo
Or, if you're not running interactively (for example, as an agent):
bashpgpm init workspace --no-tty \ --name projections-demo --repoName projections-demo \ --fullName "Ada Lovelace" --email ada@example.com \ --username ada --license MIT cd projections-demo
Import the schema
Save this DDL as schema.sql in the workspace root. The reporting view depends on the books table; pgpm will use that dependency in the plan.
bashcat > schema.sql <<'SQL' CREATE SCHEMA library; CREATE SCHEMA reporting; CREATE TABLE library.books ( id integer PRIMARY KEY, title text NOT NULL ); CREATE VIEW reporting.book_titles AS SELECT id, title FROM library.books; SQL pgpm import schema.sql --pkg library --out ./packages cat packages/library/pgpm.plan
pgpm import creates the module for you; there's no need to run pgpm init for it first. Look for the view's dependency on schemas/library/tables/books/table in pgpm.plan. Each plan entry has scripts in deploy/, revert/, and verify/.
Deploy the module
Start local Postgres, load the connection variables, and give the server time to accept connections before deploying:
bashpgpm docker start eval "$(pgpm env)" for attempt in {1..30}; do pg_isready -q && break sleep 1 done pg_isready
Once Postgres is accepting connections, deploy into a new database:
bashpgpm deploy --database projections_demo --createdb pgpm verify --database projections_demo
Or, if you're not running interactively (for example, as an agent):
bashpgpm deploy --database projections_demo --createdb --package library --yes --no-tty pgpm verify --database projections_demo --package library --no-tty
bashpsql -X -v ON_ERROR_STOP=1 -d projections_demo -c 'SELECT * FROM reporting.book_titles;'
The query shows the id and title columns with zero rows. You imported the structure, not any book data. Keep Postgres running and stay at the workspace root for the rest of the course.

