pg-sprite

module
v0.5.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: Apache-2.0

README

pg-sprite

Change the shape of live PostgreSQL tables while your application keeps reading and writing them

CI Slot Release Proof Vulnerability Scan Release

Vision · How it works · Install · Quick start · CLI guide · Docs


pg-sprite is an online schema-change engine for PostgreSQL: community, RDS, and Aurora, tested on 14 through 18. Give it a DDL statement or a desired CREATE TABLE file. It works out what the change would lock and rewrite, runs the safest sequence that reaches the same end state, and refuses with a typed verdict when it cannot prove one.

[!IMPORTANT] Preview: ready to try. Everyday changes such as adding a column, an index, or a constraint run today with short locks. Rewriting a whole table, such as changing a column's type, is in preview and runs only with --copy-and-swap. We're not at 1.0 yet, so commands and output may change between releases. pg-sprite capabilities --json says which changes are ga and which are preview.

How it works

A planner classifies each change, a router picks a strategy, and an executor carries it out:

  • Native idioms when PostgreSQL has one: CREATE INDEX CONCURRENTLY, NOT VALID + VALIDATE, fast defaults, ADD CONSTRAINT … USING INDEX.
  • Copy-and-swap for genuine rewrites: a shadow table filled in chunks while writes stream through logical decoding, checksum-verified, then swapped in. It is resumable and runs a general ALTER COLUMN TYPE today.
  • A typed refusal when neither is safe. Nothing runs, and the verdict carries a reason and class that automation can route on.

The planner is PostgreSQL's missing MySQL-style ALGORITHM= / LOCK= declaration. It proves the cost and the lock impact before anything executes (reference). Anything that is not changing a table's shape, such as data backfills or access control, is another tool's job; capabilities.md names which.

What it looks like

  • Improve: a blocking form is replaced with the safer online sequence (above; why it is safer is in safer-sequences.md).
  • Diff: a desired CREATE TABLE file in, a classified plan out (demo).
  • Refuse: no safe path exists, so nothing runs and the command exits 2 (demo).
  • Lint: blocking idioms flagged offline, no database needed (demo).

Every output shape, as text and JSON, is in cli-output-examples.md.

Install

brew install block/tap/pg-sprite

Release archives for linux and darwin on amd64 and arm64, with checksums.txt, are on the releases page. The binary is pure Go, so go install works anywhere with no C toolchain:

go install github.com/block/pg-sprite/cmd/pg-sprite@latest

Quick start

pg-sprite lint changes.sql                              # offline: flag blocking idioms

export PGSPRITE_URL='postgres://user:pass@primary:5432/app'
pg-sprite migrate --dry-run --alter 'ALTER TABLE app.orders ADD CONSTRAINT qty_positive CHECK (qty > 0)'
pg-sprite migrate --alter 'ALTER TABLE app.orders ADD CONSTRAINT qty_positive CHECK (qty > 0)'

pg-sprite pull --schema app --out schema                # one desired file per table
pg-sprite diff --schema app --desired schema/orders.sql # what would converge app.orders

Connect directly to the primary, not through a pooler (why). The CLI guide walks through each task with captured output.

Commands

Command Database What it does
migrate required Plan, route, and execute one change under bounded lock and statement budgets (copy-and-swap flags)
migrate --dry-run required The same plan against the real table; executes nothing
diff required Plan the changes that converge a live table onto a desired file; changes nothing
pull required Write one desired file per supported table in a schema
status required Show live pg-sprite sessions
reap required Drop orphan replication slots that stopped copy-and-swap runs left behind
capabilities none Print the support matrix (--json for automation)
fmt none Canonicalize a schema file
lint none Flag patterns the engine would refuse, rewrite, or gate
suggest none Show the safer form the engine would run for risky DDL

Only migrate and reap ever write. If a multi-step change fails partway, execution-model.md says what state the table is in.

What pg-sprite does not do yet

Every boundary fails closed with a typed refusal, never a silently wrong or incomplete result. The full list is in limitations.md, and the support matrix is capabilities.md.

  • Copy-and-swap is in preview and carries only ALTER COLUMN TYPE; other rewrites refuse (running it).
  • No connection poolers on pg-sprite's own connection, except Supabase's session endpoint (poolers).
  • Foreign keys a desired file adds run online (NOT VALID, then VALIDATE); dropping one runs only through migrate --alter.
  • Renames are refused unless --force names the table, since they break running application instances.
  • Destructive changes need --allow-destructive SCHEMA.TABLE, and desired plans also need --expect-fingerprint.
  • Index maintenance (DROP INDEX, REINDEX) runs from migrate --alter only as an accepted blocking change (passthrough); a desired file drops an index concurrently under --allow-destructive and --expect-fingerprint, and a partitioned table's index only as an accepted blocking drop.
  • Non-table objects such as views, functions, and triggers are outside the declarative model, apart from adding enum labels.
  • Tables are never dropped; that stays with the owner of the whole schema.

Exit codes

Exit Meaning
0 Executed through an online-safe path, or a dry run, diff, or pull found nothing to refuse
1 Failed: a PostgreSQL, operational, or usage error. A safer sequence that stopped partway keeps its committed steps, named in executed_sql
2 Refused: no online-safe path. The verdict names the typed reason and class. A migrate --desired plan refused partway keeps the statements before it
3 Committed through the accepted-blocking passthrough, without an online-safety guarantee

Gate on non-zero. The full rules, including a lost COMMIT and library callers, are in cli-output-examples.md.

Docs

Development

make setup       # one-time: configure git hooks
make build       # build ./... and bin/pg-sprite
make test        # full suite; integration tests need Docker
make test-unit   # unit tests only
make demo        # runnable tour of the CLI against a local PostgreSQL

Integration tests run against real PostgreSQL through testcontainers. testing.md covers the version matrix and the local database targets; demo/README.md covers the tour.

Contributing

Not yet; see CONTRIBUTING. Safety-relevant issue reports are welcome even at this stage.

License

Apache 2.0

Directories

Path Synopsis
cmd
pg-sprite command
Command pg-sprite is an online schema-change engine for PostgreSQL.
Command pg-sprite is an online schema-change engine for PostgreSQL.
internal
cli
Package cli defines the pg-sprite command tree (Kong): migrate and status (the optimistic front door), pull, diff, and fmt (the declarative front door), lint and suggest (the offline checker and advisor), capabilities (the embedded support matrix), and reap (the orphan-slot reaper).
Package cli defines the pg-sprite command tree (Kong): migrate and status (the optimistic front door), pull, diff, and fmt (the declarative front door), lint and suggest (the offline checker and advisor), capabilities (the embedded support matrix), and reap (the orphan-slot reaper).
cmd/gen-capabilities command
Command gen-capabilities renders the checked-in support matrix from embedded YAML.
Command gen-capabilities renders the checked-in support matrix from embedded YAML.
safety
Package safety holds repository-wide tests that pin SAFETY.md's contracts to the code, where a single package cannot legitimately speak for the whole repository.
Package safety holds repository-wide tests that pin SAFETY.md's contracts to the code, where a single package cannot legitimately speak for the whole repository.
testutil
Package testutil is the integration-test harness: a real PostgreSQL in a container plus per-test throwaway schemas.
Package testutil is the integration-test harness: a real PostgreSQL in a container plus per-test throwaway schemas.
testutil/modeltest
Package modeltest compares schemadiff models in tests.
Package modeltest compares schemadiff models in tests.
pkg
applier
Package applier turns decoded changes into shadow-table writes.
Package applier turns decoded changes into shadow-table writes.
capabilities
Package capabilities provides the embedded, validated support matrix and its Markdown renderer.
Package capabilities provides the embedded, validated support matrix and its Markdown renderer.
checkpoint
Package checkpoint persists the one durable resume record per target — the Checkpoint — in the target database, enforcing ST-1 (one row per target, written atomically), ST-2 (an incompatible record is distinguishable from a transient read error, and neither is mistaken for the absence of a record), and ST-10 (the table evolves additively, and an older engine never alters a newer one's table).
Package checkpoint persists the one durable resume record per target — the Checkpoint — in the target database, enforcing ST-1 (one row per target, written atomically), ST-2 (an incompatible record is distinguishable from a transient read error, and neither is mistaken for the absence of a record), and ST-10 (the table evolves additively, and an older engine never alters a newer one's table).
checksum
Package checksum compares the shadow table with its source and mints the proofs the cutover demands of that comparison (CO-1, CO-2, CO-3).
Package checksum compares the shadow table with its source and mints the proofs the cutover demands of that comparison (CO-1, CO-2, CO-3).
copier
Package copier fills the shadow table from its source under the table's lock session.
Package copier fills the shadow table from its source under the table's lock session.
dbconn
Package dbconn is the engine's database connectivity layer: pgx pool construction with safe session defaults (lock_timeout, statement_timeout), RDS/Aurora TLS, bounded retries for transient errors, and a helper to terminate backends blocking a session's lock acquisition.
Package dbconn is the engine's database connectivity layer: pgx pool construction with safe session defaults (lock_timeout, statement_timeout), RDS/Aurora TLS, bounded retries for transient errors, and a helper to terminate backends blocking a session's lock acquisition.
decode
Package decode owns the copy-and-swap route's logical-decoding state and the contracts its consumers depend on (ST-3, ST-4, CO-4, CO-8).
Package decode owns the copy-and-swap route's logical-decoding state and the contracts its consumers depend on (ST-3, ST-4, CO-4, CO-8).
diffplan
Package diffplan is the declarative front door as a library: a parsed desired-state schema in, the routed convergence plan out.
Package diffplan is the declarative front door as a library: a parsed desired-state schema in, the routed convergence plan out.
executor
Package executor runs schema changes against the database.
Package executor runs schema changes against the database.
internal/chunksql
Package chunksql holds the statements that put a chunk of source rows into the shadow, and the search_path and output settings they run under.
Package chunksql holds the statements that put a chunk of source rows into the shadow, and the search_path and output settings they run under.
lint
Package lint checks DDL offline for patterns the engine would refuse, rewrite, or gate.
Package lint checks DDL offline for patterns the engine would refuse, rewrite, or gate.
migrate
Package migrate is the imperative front door as a library: one parsed statement in — gate, resolve, introspect, classify, route, execute — and exactly one verdict out.
Package migrate is the imperative front door as a library: one parsed statement in — gate, resolve, introspect, classify, route, execute — and exactly one verdict out.
plan
Package plan defines the machine-readable dry-run plan report: the stable JSON contract an operator or orchestrator consumes to decide whether and how a change would execute.
Package plan defines the machine-readable dry-run plan report: the stable JSON contract an operator or orchestrator consumes to decide whether and how a change would execute.
planner
Package planner classifies schema-change statements: for each operation it decides whether PostgreSQL can run it online natively (possibly via a safer idiom it suggests), whether it needs the engine's copy-and-swap path, or whether it is refused.
Package planner classifies schema-change statements: for each operation it decides whether PostgreSQL can run it online natively (possibly via a safer idiom it suggests), whether it needs the engine's copy-and-swap path, or whether it is refused.
preflight
Package preflight verifies preconditions before the engine writes anything (invariant ST-6).
Package preflight verifies preconditions before the engine writes anything (invariant ST-6).
progress
Package progress defines the strategy-wide, machine-readable execution progress contract.
Package progress defines the strategy-wide, machine-readable execution progress contract.
refusal
Package refusal holds the routing vocabulary the core's refusals are classified in.
Package refusal holds the routing vocabulary the core's refusals are classified in.
router
Package router assigns every classified statement to an execution backend.
Package router assigns every classified statement to an execution backend.
schemachange
Package schemachange orchestrates copy-and-swap schema changes while enforcing LK-2, LK-4, and ST-5.
Package schemachange orchestrates copy-and-swap schema changes while enforcing LK-2, LK-4, and ST-5.
schemadiff
Package schemadiff builds the canonical table model both front-ends share and diffs two models into an ordered statement list.
Package schemadiff builds the canonical table model both front-ends share and diffs two models into an ordered statement list.
statement
Package statement parses SQL through the real PostgreSQL grammar (wasilibs/go-pgquery, Wasm libpg_query) and reports the facts the engine's front door needs.
Package statement parses SQL through the real PostgreSQL grammar (wasilibs/go-pgquery, Wasm libpg_query) and reports the facts the engine's front door needs.
suggest
Package suggest is the advisory surface: it maps DDL that is risky as written to the safer native form the engine would run instead, offline and without executing anything.
Package suggest is the advisory surface: it maps DDL that is risky as written to the safer native form the engine would run instead, offline and without executing anything.
verdict
Package verdict is the engine's structured outcome contract: every migrate invocation ends in exactly one verdict — executed natively, refused with a typed reason and, where one exists, a safer native idiom, or failed during execution with the executor's stable outcome code and a disclosure of what committed before the failure.
Package verdict is the engine's structured outcome contract: every migrate invocation ends in exactly one verdict — executed natively, refused with a typed reason and, where one exists, a safer native idiom, or failed during execution with the executor's stable outcome code and a disclosure of what committed before the failure.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL