Skip to main content
The generate command compares your current and desired schemas and produces golang-migrate compatible migration files. It automatically orders operations based on dependencies and generates both up and down migrations.

Usage

Flags

Examples

Basic Generation

Preview Mode

Preview what migrations would be created without writing files:

Custom Starting Version

Docker

Output Files

Generated migration files follow the golang-migrate naming convention:
migrations
000001_add_users_table.up.sql
000001_add_users_table.down.sql
000002_add_orders_table.up.sql
000002_add_orders_table.down.sql
000003_add_indexes.up.sql
000003_add_indexes.down.sql

File Format

Each migration file includes:
  • Header with metadata (timestamp, description)
  • List of changes included
  • Transaction control (BEGIN/COMMIT)
  • Idempotent DDL statements
Example up migration:
Example down migration:

Idempotent DDL

All generated DDL statements are idempotent by default:

Transaction Control

pgtofu wraps migrations in transactions when safe:
Some operations cannot run inside a transaction. pgtofu automatically handles this by splitting migrations or adding appropriate comments.

Change Ordering

pgtofu automatically orders operations based on dependencies:
  1. Extensions - Must be created first
  2. Custom Types - Enums, composites, domains
  3. Sequences - Before tables that use them
  4. Tables - In dependency order (referenced tables first)
  5. Constraints - After tables exist
  6. Indexes - After tables exist
  7. Views - After tables they reference
  8. Functions - After types and tables they use
  9. Triggers - After functions and tables
  10. TimescaleDB - Hypertables, policies, continuous aggregates
For DROP operations, the order is reversed.

Version Auto-Detection

When --start-version is not specified, pgtofu scans the output directory for existing migration files and continues from the next version:

Preview Mode

Use --preview to see what would be generated without writing files:
Output:

Handling Breaking Changes

When breaking changes are detected, pgtofu:
  1. Includes a warning comment in the migration
  2. Generates the DDL but marks it as requiring review
  3. Displays a summary of breaking changes

Troubleshooting

If no changes are detected:
  • Run pgtofu diff first to verify changes exist
  • Check that schema names match (default: public)
This usually indicates a design issue in your schema:
  • Check for circular foreign key references
  • Consider using deferrable constraints
Ensure the output directory is writable:

Applying Migrations

Use golang-migrate to apply generated migrations:

See Also