Getting Started

March 3, 2026 · View on GitHub

Installation

# Global install (recommended for CLI)
npm install -g pg-safe-migrate

# Or as a dev dependency
npm install -D pg-safe-migrate

# Or use the core library programmatically
npm install pg-safe-migrate-core

Initialize

pg-safe-migrate init

This creates:

  • ./migrations/ — directory for your SQL migration files
  • pgsm.config.json — configuration file

Create Your First Migration

pg-safe-migrate create add_users_table --with-down

This generates timestamped files:

migrations/
  20240315_143022_add_users_table.sql
  20240315_143022_add_users_table.down.sql

Edit the up migration:

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL DEFAULT '',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

And the down migration:

DROP TABLE users;

Apply Migrations

export DATABASE_URL=postgresql://localhost:5432/mydb

pg-safe-migrate up

Check Status

pg-safe-migrate status

Output:

Migration Status
────────────────

Applied (1):
  ✓ 20240315_143022_add_users_table  2024-03-15T14:30:22  42ms

Pending (0):
ℹ No pending migrations.

Lint for Safety

pg-safe-migrate lint

The linter checks for risky operations like:

  • Dropping tables or columns
  • Creating indexes without CONCURRENTLY
  • Adding NOT NULL columns without defaults

CI Gate

pg-safe-migrate check

Exits non-zero if drift, unsafe migrations, or lint errors are detected. Perfect for CI pipelines.

Next Steps