Migration Generation
The generation phase takes the detected changes from diffing and produces golang-migrate compatible migration files. pgtofu generates both “up” migrations (apply changes) and “down” migrations (revert changes).Generation Pipeline
DDL Generation
Registry Pattern
pgtofu uses a registry that maps change types to DDL builder functions:DDL Statement Structure
Generated DDL Examples
Tables
Add Table:Columns
Add Column:Indexes
Add Index:Constraints
Add Foreign Key:Views
Add View:Functions
Add/Modify Function:TimescaleDB
Create Hypertable:Migration File Format
File Naming
Files follow golang-migrate convention:version: 6-digit zero-padded number (000001, 000002, …)description: Sanitized description (lowercase, underscores)direction:upordown
File Structure
Transaction Control
Wrapped in Transactions
Most DDL operations are wrapped in transactions:Cannot Use Transactions
Some operations cannot run inside transactions:| Operation | Reason |
|---|---|
CREATE INDEX CONCURRENTLY | PostgreSQL limitation |
DROP INDEX CONCURRENTLY | PostgreSQL limitation |
CREATE DATABASE | PostgreSQL limitation |
| Some TimescaleDB operations | Extension limitation |
Idempotent DDL
All generated DDL is idempotent by default:| Statement | Idempotent Form |
|---|---|
| CREATE TABLE | CREATE TABLE IF NOT EXISTS |
| DROP TABLE | DROP TABLE IF EXISTS |
| CREATE INDEX | CREATE INDEX IF NOT EXISTS |
| DROP INDEX | DROP INDEX IF EXISTS |
| ADD COLUMN | Check column existence first |
| DROP COLUMN | DROP COLUMN IF EXISTS |
Down Migrations
Down migrations reverse up migrations:| Up Migration | Down Migration |
|---|---|
| CREATE TABLE | DROP TABLE |
| ADD COLUMN | DROP COLUMN |
| CREATE INDEX | DROP INDEX |
| ADD CONSTRAINT | DROP CONSTRAINT |
| CREATE FUNCTION | DROP FUNCTION |
Limitations
Some changes cannot be fully reversed:- Data loss - Dropped columns/tables cannot recover data
- Type narrowing - May lose precision
- Dropped defaults - Original default may be unknown
Safety Features
Breaking Change Warnings
Data Migration Indicators
Safe Identifier Quoting
All identifiers are properly quoted:Version Auto-Detection
When--start-version is not specified:
- Scan output directory for existing migrations
- Parse version numbers from filenames
- Start from next available version
See Also
- Dependency Resolution - How operations are ordered
generatecommand - CLI reference- CI/CD Integration - Automated migration generation