Skip to content

branch

The branch command lists existing branches or creates a new branch from the current database state.

Terminal window
# List all branches
pgbranch branch
# Create a new branch
pgbranch branch <name>
ArgumentDescription
nameName for the new branch (optional)
Terminal window
pgbranch branch

Output:

main
* feature-auth
feature-payments

The * indicates the current branch.

Terminal window
pgbranch branch feature-notifications

Output:

Branch 'feature-notifications' created

After initializing pgbranch, create your first branch:

Terminal window
pgbranch init -d myapp_dev
pgbranch branch main

When you create a branch, pgbranch:

  1. Terminates active connections to the working database
  2. Creates a template database as a snapshot
  3. Records metadata (creation time, parent branch)

The template database is named: pgbranch_<branch_name>_<project_hash>

Working database: myapp_dev
CREATE DATABASE
pgbranch_feature_auth_abc123
TEMPLATE myapp_dev
Snapshot stored as template database

Branch names should:

  • Contain only alphanumeric characters, hyphens, and underscores
  • Not start with a number
  • Be reasonably short (PostgreSQL has a 63-character limit on identifiers)

Good branch names:

main
feature-auth
bugfix-login-issue
v2-schema

A common strategy is to mirror your git branch names:

Terminal window
git checkout -b feature/user-profiles
pgbranch branch feature-user-profiles

Create branches at significant points:

Terminal window
# After fresh migration
pgbranch branch clean-schema
# After seeding test data
pgbranch branch with-seed-data
# Before risky migration
pgbranch branch pre-migration

To see more information about branches, use the log command:

Terminal window
pgbranch log

Output:

* main (current)
Created: 2024-01-15 10:30:00
Parent: -
feature-auth
Created: 2024-01-15 14:22:00
Parent: main

Each branch creates a complete database copy. Monitor disk usage:

Terminal window
# Check PostgreSQL database sizes
psql -c "SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname))
FROM pg_database WHERE datname LIKE 'pgbranch_%';"

Use pgbranch prune to clean up old branches:

Terminal window
pgbranch prune -d 7 # Remove branches not accessed in 7 days
Terminal window
# Start from main
pgbranch checkout main
# Create feature branch
pgbranch branch feature-new-api
# Work on feature...
# Run migrations, add test data
# Switch back to main for a hotfix
pgbranch checkout main
pgbranch branch hotfix-critical-bug
Terminal window
# Save current state
pgbranch branch before-migration
# Run migration
npm run migrate
# If migration fails, restore
pgbranch checkout before-migration
  • checkout - Switch to a different branch
  • delete - Delete a branch
  • log - View branch history
  • status - Show current branch