pg-schema-diff
CLAUDE.md889 starsChanged 11 months agoMITView on GitHub
A declarative schema migration tool for PostgreSQL that computes the difference between two database schemas and generates minimal, optimized SQL to migrate from one to the other with zero-downtime where possible. Problem Solved: Developers declare their desired database schema in DDL files, and pg-schema-diff automatically generates safe, optimized migration SQL that minimizes downtime and locks. Key Features: - Computes diffs between schemas (DDL files, databases, or directories) - Generates SQL using native Postgres online operations (concurrent index builds, online constraint…
The file
We split this CLAUDE.md into the rules it gives an agent
11 rules. About 0 are common, 1 is distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 57
Run make sqlc to regenerate queries.sql.go
- Very specific: line 139
Online Constraint Validation: Add as NOT VALID, validate separately
- Very specific: line 197
Add type to internal/schema/schema.go
- Very specific: line 198
Add query to internal/queries/queries.sql, run make sqlc
- Very specific: line 199
Update schema fetching logic, schema structs, and tests in internal/schema
- Very specific: line 200
Add diffing logic in pkg/diff/diff.go
- Very specific: line 201
Add SQL generation logic in pkg/diff/x_sql_generator.go
- Very specific: line 202
Add acceptance tests in internal/migration_acceptance_tests/
- Very specific: line 205
Use fmt.Errorf with %w for error wrapping.
- Very specific: line 208
Use testify/assert and testify/require
- Distinctive: line 210
Test cases are typically table-driven
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
pg-schema-diff
A declarative schema migration tool for PostgreSQL that computes the difference between two database schemas and generates minimal, optimized SQL to migrate from one to the other with zero-downtime where possible.
Project Overview
Problem Solved: Developers declare their desired database schema in DDL files, and pg-schema-diff automatically generates safe, optimized migration SQL that minimizes downtime and locks.
Key Features:
- Computes diffs between schemas (DDL files, databases, or directories)
- Generates SQL using native Postgres online operations (concurrent index builds, online constraint validation)
- Provides hazard warnings for dangerous operations
- Validates migration plans against temporary databases before execution
Directory Structure
cmd/pg-schema-diff/ # CLI entry point (Cobra-based)
├── plan_cmd.go # 'plan' subcommand - generates migration SQL
├── apply_cmd.go # 'apply' subcommand - applies migrations
├── flags.go # Flag parsing and DB connection handling
pkg/ # Public API packages
├── diff/ # Core diffing and plan generation (main library interface)
├── tempdb/ # Temporary database factory for plan validation
├── log/ # Logging interface
├── schema/ # Public schema API wrapper
├── sqldb/ # Database queryable interface
internal/ # Internal implementation
├── schema/ # Complete schema representation types (schema.go is 46KB)
├── queries/ # SQL queries via sqlc for schema introspection
├── migration_acceptance_tests/ # Comprehensive test suite (24 test files)
├── pgengine/ # Postgres engine management for tests
├── pgdump/ # pg_dump integration
├── graph/ # Dependency graph for statement orderingKey Packages
pkg/diff/ - Core Diffing Engine
plan_generator.go: Orchestrates plan generation and validationsql_generator.go: Generates SQL statements for all object types (2,700+ lines)sql_graph.go: Dependency graph for correct statement orderingschema_source.go: Schema sources (DDL files, database, directories)
internal/schema/ - Schema Representation
Core types in schema.go:
Schema: Top-level container for all database objectsTable: Tables with columns, constraints, policies, triggersIndex: Index definitions including partial indexes and expressionsColumn,ForeignKeyConstraint,CheckConstraint,View,Function, etc.
internal/queries/ - Database Queries
Uses sqlc for type-safe SQL queries. To modify:
- Edit
queries.sql - Run
make sqlcto regeneratequeries.sql.go
Development Commands
# Run all tests (requires Docker or local Postgres)
go test -v -race ./... -timeout 30m
# Run specific acceptance tests
go test -v ./internal/migration_acceptance_tests/... -run TestIndexAcceptance
# Lint
make lint
# Fix lint issues
make lint_fix
# Regenerate sqlc code
make sqlc
# Tidy dependencies
make go_mod_tidyTesting
Acceptance Tests
Located in internal/migration_acceptance_tests/. Each test file covers specific features:
index_cases_test.go: Index operationstable_cases_test.go: Table operationscolumn_cases_test.go: Column operationscheck_constraint_cases_test.go,foreign_key_constraint_cases_test.go: Constraintsview_cases_test.go,function_cases_test.go,trigger_cases_test.go, etc.
Test case structure:
acceptanceTestCase{
name: "test name",
oldSchemaDDL: []string{"CREATE TABLE ..."},
newSchemaDDL: []string{"CREATE TABLE ... (modified)"},
expectedHazardTypes: []diff.MigrationHazardType{...},
expectedPlanDDL: []string{"ALTER TABLE ..."}, // optional: assert exact DDL
expectEmptyPlan: false, // optional: assert no changes
planOpts: []diff.PlanOpt{...}, // optional: custom plan options
}Running Tests with Docker
docker build -f build/Dockerfile.test --build-arg PG_MAJOR=15 -t pg-schema-diff-test .
docker run pg-schema-diff-testKey Concepts
Migration Hazards
Operations are flagged with hazard types:
MigrationHazardTypeAcquiresAccessExclusiveLock: Full table lockMigrationHazardTypeDeletesData: Potential data lossMigrationHazardTypeIndexBuild: Performance impact during buildMigrationHazardTypeIndexDropped: Query performance may degradeMigrationHazardTypeCorrectness: Potential correctness issues
Plan and Statements
type Plan struct {
Statements []Statement
CurrentSchemaHash string // For validation before applying
}
type Statement struct {
DDL string // SQL to execute
Timeout time.Duration // statement_timeout
LockTimeout time.Duration // lock_timeout
Hazards []MigrationHazard
}Online Migration Techniques
- Concurrent Index Building:
CREATE INDEX CONCURRENTLY - Online Index Replacement: Rename old, build new concurrently, drop old
- Online NOT NULL: Uses check constraints temporarily
- Online Constraint Validation: Add as
NOT VALID, validate separately
CLI Usage
# Generate migration plan (from database to DDL files)
pg-schema-diff plan \
--from-dsn "postgres://user:pass@localhost:5432/mydb" \
--to-dir ./schema
# Generate plan between two databases
pg-schema-diff plan \
--from-dsn "postgres://..." \
--to-dsn "postgres://..."
# Apply migration (requires hazard approval)
pg-schema-diff apply \
--from-dsn "postgres://user:pass@localhost:5432/mydb" \
--to-dir ./schema \
--allow-hazards INDEX_BUILD,ACQUIRES_ACCESS_EXCLUSIVE_LOCK
# Output formats: sql (default), json, pretty
pg-schema-diff plan --from-dsn "..." --to-dir ./schema --output-format jsonLibrary Usage
import (
"github.com/stripe/pg-schema-diff/pkg/diff"
"github.com/stripe/pg-schema-diff/pkg/tempdb"
)
// Create temp database factory for plan validation
tempDbFactory, _ := tempdb.NewOnInstanceFactory(ctx, func(ctx context.Context, dbName string) (*sql.DB, error) {
return sql.Open("postgres", fmt.Sprintf(".../%s", dbName))
})
// Define schema sources
currentSchema := diff.DBSchemaSource(db) // db is *sql.DB or sqldb.Queryable
targetSchema, _ := diff.DirSchemaSource([]string{"./schema"}) // returns (SchemaSource, error)
// Generate plan
plan, _ := diff.Generate(ctx, currentSchema, targetSchema,
diff.WithTempDbFactory(tempDbFactory),
)
// Apply statements (set timeouts before each statement)
for _, stmt := range plan.Statements {
conn.ExecContext(ctx, fmt.Sprintf("SET SESSION statement_timeout = %d", stmt.Timeout.Milliseconds()))
conn.ExecContext(ctx, fmt.Sprintf("SET SESSION lock_timeout = %d", stmt.LockTimeout.Milliseconds()))
conn.ExecContext(ctx, stmt.ToSQL())
}Code Patterns
Adding New Schema Object Support
- Add type to
internal/schema/schema.go - Add query to
internal/queries/queries.sql, runmake sqlc - Update schema fetching logic, schema structs, and tests in
internal/schema - Add diffing logic in
pkg/diff/diff.go - Add SQL generation logic in
pkg/diff/x_sql_generator.go - Add acceptance tests in
internal/migration_acceptance_tests/
Error Handling
Use fmt.Errorf with %w for error wrapping. Functions return error as last return value.
Testing Conventions
- Use
testify/assertandtestify/require - Acceptance tests use shared Postgres via
pgengine - Test cases are typically table-driven
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

