Core Concepts
pgtofu transforms database schema management from an imperative process (writing migrations) to a declarative one (defining desired state). This page explains the key concepts that make this possible.The Four Phases
pgtofu operates in four distinct phases:Extract
Connect to PostgreSQL and export the current schema as JSON
Parse
Parse SQL files defining your desired schema into JSON
Diff
Compare current and desired schemas to detect changes
Generate
Create ordered migration files from detected changes
Declarative vs Imperative
Imperative Approach (Traditional)
With traditional migration tools, you manually write each change:- Hard to see current schema state
- Easy to miss dependencies
- Manual ordering required
- Merge conflicts are common
Declarative Approach (pgtofu)
With pgtofu, you define the desired end state:- Compares with current database
- Detects what changed
- Orders changes correctly
- Generates safe migrations
Schema Representation
Both extracted and parsed schemas are normalized to the same JSON format:- SQL formatting differences
- Type alias variations (
VARCHARvscharacter varying) - Whitespace and comments
Change Detection
The differ compares schemas field-by-field and detects:| Category | Examples |
|---|---|
| Additions | New tables, columns, indexes, constraints |
| Deletions | Removed objects |
| Modifications | Changed types, defaults, definitions |
- SAFE - Non-breaking additions
- POTENTIALLY_BREAKING - May affect applications
- BREAKING - May cause data loss
- DATA_MIGRATION_REQUIRED - Cannot be automated
Dependency Resolution
pgtofu uses topological sorting to order changes correctly:Migration Generation
The generator creates golang-migrate compatible files with:- Idempotent DDL -
IF EXISTS/IF NOT EXISTSclauses - Transaction control - Wrapped in
BEGIN/COMMITwhen safe - Reversibility - Both up and down migrations generated
- Safety warnings - Breaking changes are flagged
Key Principles
Single Source of Truth
Single Source of Truth
Your SQL files in version control are the authoritative schema definition. The database state is derived, not authoritative.
Correctness Over Convenience
Correctness Over Convenience
pgtofu prioritizes generating safe, correct migrations over minimizing migration count or simplifying output.
Explicit Over Implicit
Explicit Over Implicit
All schema objects must be explicitly defined. pgtofu doesn’t infer or assume schema elements.
Reproducibility
Reproducibility
Given the same current schema and desired schema, pgtofu always generates the same migrations.