pgmold
PostgreSQL schema-as-code management tool. Define schemas in native PostgreSQL DDL, diff against live databases, plan migrations, and apply them safely.
Features
- Schema-as-Code: Define PostgreSQL schemas in native SQL DDL files
- Introspection: Read schema from live PostgreSQL databases
- Diffing: Compare schemas and generate migration plans
- Safety: Lint rules prevent destructive operations without explicit flags
- Drift Detection: Monitor for schema drift in CI/CD
- Transactional Apply: All migrations run in a single transaction
- Partitioned Tables: Full support for
PARTITION BYandPARTITION OFsyntax
How pgmold Works
┌─────────────────────┐ ┌─────────────────────┐
│ Schema Files │ │ Live Database │
│ (Desired State) │ │ (Current State) │
└──────────┬──────────┘ └──────────┬──────────┘
│ │
└───────────┬───────────────┘
▼
┌─────────────────┐
│ pgmold diff │
│ (compare) │
└────────┬────────┘
▼
┌─────────────────┐
│ Generated SQL │
│ (only changes) │
└─────────────────┘
Example:
Your schema file says:
(
id UUID PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL, -- NEW
created_at TIMESTAMP
);
Database currently has:
(
id UUID PRIMARY KEY,
name TEXT NOT NULL,
created_at TIMESTAMP
);
pgmold generates only the delta:
users ADD COLUMN email TEXT NOT NULL;
Installation
For the latest version with partitioned table support (until the sqlparser fork is merged upstream):
Quick Start
# 1. Create a schema file
# 2. See what would change
# 3. Apply the migration
Usage
# Compare SQL schema to live database
# Generate migration plan
# Generate rollback plan (reverse direction)
# Apply migrations (with safety checks)
# Apply with destructive operations allowed
# Dry run (preview SQL without executing)
# Lint schema
# Monitor for drift
Guides
Multi-File Schemas
Organize your schema across multiple files using directories or glob patterns:
# Load all SQL files from a directory (recursive)
# Use glob patterns
# Multiple sources
Example directory structure:
schema/
├── enums.sql # CREATE TYPE statements
├── tables/
│ ├── users.sql # users table + indexes
│ └── posts.sql # posts table + foreign keys
└── functions/
└── triggers.sql # stored procedures
Duplicate definitions (same table/enum/function in multiple files) will error immediately with clear file locations.
Filtering Objects
Filter which objects to include in comparisons using name patterns or object types.
Filter by name pattern:
# Include only objects matching patterns
# Exclude objects matching patterns
Filter by object type:
# Only compare tables and functions (ignore extensions, views, triggers, etc.)
# Exclude extensions from comparison
Combine type and name filters:
# Compare only functions matching 'api_*', excluding internal ones
Filter nested types within tables:
# Compare tables without RLS policies
# Compare only table structure (no indexes, constraints, or policies)
Available object types:
- Top-level:
extensions,tables,enums,domains,functions,views,triggers,sequences,partitions - Nested (within tables):
policies,indexes,foreignkeys,checkconstraints
Extension Objects
By default, pgmold automatically excludes objects owned by extensions (e.g., PostGIS functions, pg_trgm operators). This prevents extension-provided objects from appearing in diffs.
# Include extension objects if needed (e.g., for full database dumps)
Adopting pgmold in an Existing Project
If you have a live database with existing schema (and possibly a migration-based workflow), use pgmold dump to create a baseline:
# Export current database schema to SQL files
# For specific schemas only
# Split into multiple files by object type
The --split option creates separate files for extensions, types, sequences, tables, functions, views, triggers, and policies.
This exports your live database schema as SQL DDL. Now your schema files match the database exactly, and pgmold plan will show 0 operations.
Workflow After Baseline
- Make changes by editing the SQL schema files
- Preview with
pgmold plan --schema sql:schema/ --database db:postgres://localhost/mydb - Apply with
pgmold apply --schema sql:schema/ --database db:postgres://localhost/mydb
Integrating with Existing Migration Systems
pgmold is declarative (like Terraform) - it computes diffs and applies directly rather than generating numbered migration files. If you need to maintain compatibility with an existing migration system:
# Generate a numbered migration file automatically
# Creates: migrations/0044_add_email_column.sql
# Or manually capture output
The migrate generate command auto-detects the next migration number by scanning existing files.
This lets you use pgmold for diffing while keeping your existing migration runner.
Safety Rules
By default, pgmold blocks destructive operations:
DROP TABLErequires--allow-destructiveDROP COLUMNrequires--allow-destructiveDROP ENUMrequires--allow-destructive- Type narrowing produces warnings
SET NOT NULLproduces warnings (may fail on existing NULLs)
Set PGMOLD_PROD=1 to enable production mode, which blocks table drops entirely.
Comparison with Other Tools
| Feature | pgmold | dbmate | goose | golang-migrate | Flyway | Sqitch |
|---|---|---|---|---|---|---|
| Approach | Declarative | Migration-based | Migration-based | Migration-based | Migration-based | Change-based |
| Schema Definition | Native SQL | Raw SQL | SQL/Go | Raw SQL | SQL/Java | Native SQL |
| Auto-generates Migrations | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| Multi-DB Support | PostgreSQL only | ✅ | ✅ | ✅ | ✅ | ✅ |
| Drift Detection | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ |
| Safety Linting | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| Production Mode | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| RLS Policy Support | ✅ | Manual | Manual | Manual | Manual | Manual |
| Dependency Ordering | ✅ Auto | Timestamp | Version | Version | Version | Declared |
| Transactional DDL | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
When to Choose pgmold
- PostgreSQL-only projects where deep PG integration matters
- Declarative schema management (like Terraform for databases)
- CI/CD drift detection to catch manual schema changes
- Safety-first workflows with destructive operation guardrails
- RLS policies as first-class citizens
When to Choose Alternatives
- Multi-database support → dbmate, golang-migrate, Flyway
- Go code in migrations → goose
- Enterprise features → Flyway
- Complex dependency graphs → Sqitch
- Rails ecosystem → ActiveRecord Migrations
- Node.js ORM → Sequelize
Development
# Build
# Test
# Run integration tests (requires Docker)
License
MIT