pgmigrate

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

pgmigrate

ci Go Reference

Applies a library's embedded migrations into a Postgres schema that library owns — idempotently, safely under concurrency — and reconciles the declarative state migrations cannot express.

Status: implemented, pre-release. Extracted from the two independently written implementations in audit and iam. The conformance suite in pgmigratetest runs against a real Postgres; audit and iam have not yet been switched over to it.

The problem it solves

A library whose tables live in its consumer's database cannot use the consumer's migration sequence: two independent migration owners collide on a single version table. So each library owns a Postgres schema and keeps its version table inside it, and applies its own migrations from its own embedded files.

Three things in that are easy to get wrong, and one of them fails silently:

  1. Versioned versus reconciled. Putting privilege grants in a versioned migration is a trap: the migration records itself as applied, so a deployment that later renames its application role comes up with no privilege separation at all while the migrator reports everything applied. Declarative state — roles, grants, revokes, partitions — must be asserted on every run, not migrated once.
  2. The schema must exist before the migrator runs, because the version table lives in the schema and the migrator needs to create it.
  3. The advisory lock key must derive from the library's identity, so concurrent starts serialize and a library's lock cannot collide with its consumer's own migrations in the same cluster.

Shape

Up and Status, taking a narrow database interface rather than a dependency on any connection-management library. The caller supplies its schema name, its embedded migration files, and its module identity.

err := pgmigrate.Up(ctx, migrationPool, pgmigrate.Config{
    Schema:     "example",
    Identity:   "github.com/laenenai/example/internal/migrate",
    Migrations: migrations.FS,
    Reconcilers: []pgmigrate.Reconciler{{
        Name: "privileges",
        Reconcile: func(ctx context.Context, tx pgmigrate.Tx) error {
            if err := pgmigrate.EnsureRole(ctx, tx, appRole); err != nil {
                return err
            }
            return pgmigrate.AssertPrivileges(ctx, tx, pgmigrate.Privileges{
                Schema: "example", Role: appRole, SchemaUsage: true,
                Tables: []pgmigrate.TablePrivileges{{
                    Table:  "widget",
                    Grant:  []pgmigrate.Privilege{pgmigrate.PrivilegeSelect, pgmigrate.PrivilegeInsert},
                    Revoke: []pgmigrate.Privilege{pgmigrate.PrivilegeUpdate, pgmigrate.PrivilegeDelete},
                }},
                RevokeFromPublic: true,
            })
        },
    }},
})

DB is two methods, Exec and Begin, which *pgxpool.Pool, *pgx.Conn and pgx.Tx all satisfy with no wrapper at the call site. goose additionally needs a database/sql handle, which pgx's own interfaces cannot express, so a handle that is not a *pgxpool.Pool implements StdDBOpener to say how to produce one.

Reconcilers are supplied by the caller, not built in. This module owns when and how reconciliation runs — inside the lock, in one transaction, after the versioned migrations, on every Up — and knows nothing about what is being reconciled. That line is what keeps it from accumulating every consumer's partitioning strategy. audit reconciles hash and range partitions and an append-only privilege set; iam reconciles neither, and pays nothing for the phase. Example_callerSuppliedReconcilers in example_test.go reproduces both of audit's against this module's public surface, so the claim that the contract is expressive enough is checked by the compiler.

The declarative helpers the module does provide are generic: EnsureRole ensures a NOLOGIN role with no cluster-wide attributes exists, AssertPrivileges asserts exactly one grant set, and ExecIdempotent is the savepoint discipline every reconciler that creates anything needs.

The shared ledger

A deployment that wants one place to read every module's schema state sets Config.Module:

err := pgmigrate.Up(ctx, migrationPool, pgmigrate.Config{
    Schema:     "example",
    Module:     "example",
    Identity:   "github.com/laenenai/example/internal/migrate",
    Migrations: migrations.FS,
})

The version table becomes migrations.goose_migrations:

create schema if not exists migrations;

create table migrations.goose_migrations (
    module     text        not null,
    version    bigint      not null,
    applied_at timestamptz not null default now(),
    primary key (module, version)
);

module is the caller's stable name (eventstore, projections, session), and version is the migration's numeric prefix. The table is outside every module schema, so a migration that drops and recreates its own schema cannot erase its history. A goose_db_version zero row is inserted per module; it is bookkeeping, not a migration.

The ledger is per database, not global to the process. A module pointed at another database gets that database's migrations.goose_migrations under the same module name. That is what makes a later one-schema-per-database (or one-schema-per-server) split a DSN change rather than a code change.

Up and Status check the catalog before any DDL. A maintenance role can pre-create migrations.goose_migrations and grant module migration roles only USAGE on the schema and SELECT, INSERT, UPDATE, DELETE on the table; a module joining an existing ledger inserts its zero row with INSERT and performs no CREATE. Module and LedgerSchema are validated as plain identifiers, and VersionTable is rejected with Module: the shared table's shape is fixed.

The migration pool is not the runtime pool

The handle passed to Up holds the migration rights. Runtime work uses a separate pool on the application role. They are different credentials, not two states of one session: SET ROLE is reversible with RESET ROLE, so one owner connection narrowing itself makes privilege separation per-session and dependent-on-remembering, and forgetting to set it is a silent escalation with no trace. Two pools make it structural — the runtime credential does not possess the mutating rights at all. Open the migration pool, migrate, close it; migration is a startup activity, and a long-lived owner pool in the process is a standing escalation target for no benefit.

What it does not do

Connection pooling or RLS session context; any consumer's actual migrations; moving a tenant between databases, which is a different thing entirely; query building.

Testing

mise run test is the inner loop: go test ./... -short, no containers and no databases. mise run test-all runs everything, including the conformance suite against a pgvector/pgvector:pg18 container started by testcontainers-go. Set TEST_DATABASE_URL to use a running server instead; each test still gets its own uniquely named database.

A consumer runs the suite against its own handle:

func TestPgmigrateConformance(t *testing.T) {
    pgmigratetest.RunMigrateSuite(t, func(t *testing.T) pgmigrate.DB {
        return myHarness.Start(t).Pool()
    })
}

The suite, not the DB interface and not the doc comments, is the authoritative description of the contract's edge-case behaviour.

Documentation

  • CHARTER.md — including why it is named pgmigrate and not migrate
  • api.txt — the public surface as a golden file, diffed in CI

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package pgmigrate applies a library's own embedded migrations into a Postgres schema that library owns — idempotently and safely under concurrency — and reconciles the declarative state that migrations cannot express.

It exists because two increments built it twice. On 2026-10-23 the iam and audit modules were implemented in parallel by independent agents that could not see each other's work, and both produced the same machinery: a session-level advisory lock around Up, a lock key that is the CRC32 (IEEE) checksum of the migration package's import path, the same poll period and retry count, the same Up-and-Status surface, and a schema per module with its own version table inside it. Same design, same constants, the same reasoning written out twice, and keys differing only because the import paths did.

Three things in that are easy to get wrong, and one fails silently

  1. Versioned versus reconciled. Putting privilege grants in a versioned migration is a trap: the migration records itself as applied, so a deployment that later renames its application role comes up with no privilege separation at all while the migrator reports everything applied. Declarative state — roles, grants, revokes, partitions — must be asserted on every run, not migrated once.
  2. The schema must exist before the migrator runs, because the version table lives in the schema and the migrator needs to create it first. Up creates it.
  3. The advisory lock key must derive from the library's identity, so that N processes starting against one database serialize instead of racing, and so a library's lock cannot collide with its consumer's own migrations in the same cluster. A hand-chosen constant collides eventually.

The shared ledger

A deployment that wants one place to read every module's state sets Config.Module. The version table becomes Config.LedgerSchema + "." + DefaultSharedVersionTable — by default migrations.goose_migrations — with one row per module and version. The ledger is deliberately outside every module schema, so a migration that drops and recreates its own schema cannot erase its history. It is per database, not global to a process: a module pointed at another database gets that database's ledger under the same module name, which is what makes a later one-schema-per-database split a configuration change.

The shared store implements goose's database.Store directly. It checks the catalog before any DDL, so a ledger pre-created by a maintenance role works with DML grants only, and it is module-aware: a new module joining an existing table inserts its zero row with INSERT, no CREATE.

Reconcilers are supplied by the caller, not built in

This module owns when and how reconciliation runs — inside the lock, in one transaction, after the versioned migrations, on every Up — and knows nothing about what is being reconciled. audit reconciles hash and range partitions and an append-only privilege set; iam reconciles neither. Neither of those moved in here, and that line is what keeps this module from accumulating every consumer's partitioning strategy.

The declarative helpers it does provide are generic: EnsureRole ensures a NOLOGIN role exists, AssertPrivileges asserts exactly one grant set, and ExecIdempotent is the savepoint discipline every reconciler that creates anything needs.

The pool handed to Up is a migration pool

It holds the migration rights. Runtime work uses a separate pool on the application role. The two are different credentials, not two states of one session: SET ROLE is reversible with RESET ROLE, so one owner connection narrowing itself makes privilege separation per-session and dependent-on-remembering, and forgetting to set it is a silent escalation. Two pools make it structural — the runtime credential does not possess the mutating rights at all. Open the migration pool, migrate, close it; migration is a startup activity, and a long-lived owner pool in the process is a standing escalation target for no benefit.

What it does not do

Connection pooling, handle lifecycle or row-level-security session context; any consumer's actual migrations; moving a tenant between pools, which is a different thing entirely; query building; any domain concept.

Where the contract is written down

The conformance suite in pgmigratetest, not this doc comment and not the DB interface, is the authoritative description of the edge-case behaviour: that migrations are applied once and are idempotent on re-run, that the version table lands in the caller's schema and not in public, that two callers' schemas do not collide, that concurrent callers do not double-apply, that reconcilers run inside the lock and on every Up, that a reconciler failure aborts Up without being recorded as applied, and that Status reports pending before Up. A consumer runs it against its own handle.

This file carries the module's aliases, sentinel errors, exported constants and entry points — and no logic. Every function here is a one-line forward to an internal package; the reason they are here at all is that Go's internal rule makes anything not re-exported here unreachable from outside the module, and a facade that hides what the module is for is not a facade.

Example (CallerSuppliedReconcilers)

Example_callerSuppliedReconcilers reproduces, against this module's public surface and nothing else, the two reconcilers audit has today: the hash and range partitions of its event table, and its append-only privilege set. It is the evidence for the charter's load-bearing claim — that the reconciler contract is expressive enough for a real consumer's declarative state without that consumer's shape leaking in here — and the evidence is checked by the compiler rather than asserted in a doc comment.

Nothing in it needs a database, so it has no Output comment: Go compiles an example without one and does not run it, which is exactly the guarantee wanted.

Read it for what is absent. This module has no notion of a partition, a modulus, a month, a window, an append-only table or a writable head row. All of that is in the closure, where it belongs, and the only things it borrows are generic: ExecIdempotent's savepoint discipline, EnsureRole and AssertPrivileges.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/laenenai/pgmigrate"
)

func main() {
	// The consumer's own configuration and its own sentinel, neither of
	// which this module knows anything about.
	const (
		schema  = "audit"
		appRole = "audit_app"

		hashPartitions = 64
		monthsBehind   = 1
		monthsAhead    = 12
	)
	errInvalidConfig := errors.New("audit: invalid configuration")

	now := func() time.Time { return time.Now().UTC() }
	monthOf := func(t time.Time) time.Time {
		u := t.UTC()
		return time.Date(u.Year(), u.Month(), 1, 0, 0, 0, 0, time.UTC)
	}

	// Layer 2: the partitions. The modulus is fixed the first time and
	// refuses to change afterwards, because changing it redistributes every
	// tenant's rows — a data migration, not a configuration edit. The
	// refusal is returned as the consumer's own sentinel, and Up wraps it
	// with %w and no sentinel of its own, so errors.Is against
	// errInvalidConfig still matches at the call site.
	partitions := pgmigrate.Reconciler{
		Name: "partitions",
		Reconcile: func(ctx context.Context, tx pgmigrate.Tx) error {
			var existing int
			err := tx.QueryRow(ctx,
				`SELECT count(*) FROM pg_inherits WHERE inhparent = ($1 || '.event')::regclass`,
				schema,
			).Scan(&existing)
			if err != nil {
				return fmt.Errorf("count hash partitions: %w", err)
			}

			switch {
			case existing == 0:
				for i := range hashPartitions {
					stmt := fmt.Sprintf(
						`CREATE TABLE IF NOT EXISTS %s.event_h%d PARTITION OF %s.event `+
							`FOR VALUES WITH (MODULUS %d, REMAINDER %d) PARTITION BY RANGE (recorded_at)`,
						schema, i, schema, hashPartitions, i)
					if err := pgmigrate.ExecIdempotent(ctx, tx, stmt); err != nil {
						return fmt.Errorf("create hash partition %d: %w", i, err)
					}
				}
			case existing != hashPartitions:
				return fmt.Errorf("%w: event already has %d hash partitions but HashPartitions is %d",
					errInvalidConfig, existing, hashPartitions)
			}

			// The monthly window inside each hash partition, extended by
			// every Up — which is how a library-applied migration model
			// keeps the window ahead of the present.
			start := monthOf(now()).AddDate(0, -monthsBehind, 0)
			for i := range hashPartitions {
				deflt := fmt.Sprintf(
					`CREATE TABLE IF NOT EXISTS %s.event_h%d_default PARTITION OF %s.event_h%d DEFAULT`,
					schema, i, schema, i)
				if err := pgmigrate.ExecIdempotent(ctx, tx, deflt); err != nil {
					return fmt.Errorf("create default partition of hash %d: %w", i, err)
				}
				for n := range monthsBehind + monthsAhead + 1 {
					month := start.AddDate(0, n, 0)
					stmt := fmt.Sprintf(
						`CREATE TABLE IF NOT EXISTS %s.event_h%d_%s PARTITION OF %s.event_h%d `+
							`FOR VALUES FROM ('%s') TO ('%s')`,
						schema, i, month.Format("200601"), schema, i,
						month.Format("2006-01-02 15:04:05+00"),
						month.AddDate(0, 1, 0).Format("2006-01-02 15:04:05+00"))
					if err := pgmigrate.ExecIdempotent(ctx, tx, stmt); err != nil {
						return fmt.Errorf("create range partition %s of hash %d: %w", month.Format("200601"), i, err)
					}
				}
			}
			return nil
		},
	}

	// Layer 3: the privileges that are the actual append-only mechanism.
	// The role name is configuration precisely because the REVOKE names it,
	// which is why this cannot be a versioned migration: a deployment that
	// renamed the role would have the migration skipped and come up with no
	// separation at all while the migrator reported everything applied.
	privileges := pgmigrate.Reconciler{
		Name: "privileges",
		Reconcile: func(ctx context.Context, tx pgmigrate.Tx) error {
			if err := pgmigrate.EnsureRole(ctx, tx, appRole); err != nil {
				return err
			}
			return pgmigrate.AssertPrivileges(ctx, tx, pgmigrate.Privileges{
				Schema:      schema,
				Role:        appRole,
				SchemaUsage: true,
				Tables: []pgmigrate.TablePrivileges{
					{
						// The history: append and read, and nothing else.
						Table: "event",
						Grant: []pgmigrate.Privilege{pgmigrate.PrivilegeSelect, pgmigrate.PrivilegeInsert},
						Revoke: []pgmigrate.Privilege{
							pgmigrate.PrivilegeUpdate, pgmigrate.PrivilegeDelete, pgmigrate.PrivilegeTruncate,
							pgmigrate.PrivilegeReferences, pgmigrate.PrivilegeTrigger,
						},
					},
					{
						// The head row is the one writable surface: an
						// append has to move the head. DELETE stays
						// revoked, because deleting a head row would let an
						// appender restart a chain at sequence one.
						Table: "chain_head",
						Grant: []pgmigrate.Privilege{
							pgmigrate.PrivilegeSelect, pgmigrate.PrivilegeInsert, pgmigrate.PrivilegeUpdate,
						},
						Revoke: []pgmigrate.Privilege{
							pgmigrate.PrivilegeDelete, pgmigrate.PrivilegeTruncate,
							pgmigrate.PrivilegeReferences, pgmigrate.PrivilegeTrigger,
						},
					},
				},
				RevokeFromPublic: true,
			})
		},
	}

	// What the consumer's own Migrate function is, in full. The pool it
	// passes is a distinct, short-lived migration pool on the owner role:
	// opened here, closed when this returns. Runtime work uses a separate
	// pool on appRole, which does not possess these rights at all.
	_ = func(ctx context.Context, migrationPool pgmigrate.DB) error {
		return pgmigrate.Up(ctx, migrationPool, pgmigrate.Config{
			Schema:      schema,
			Identity:    "github.com/laenenai/audit/internal/migrate",
			Migrations:  nil, // the consumer's own embed.FS
			Reconcilers: []pgmigrate.Reconciler{partitions, privileges},
		})
	}
}

Index

Examples

Constants

View Source
const (
	PrivilegeSelect     = migrate.PrivilegeSelect
	PrivilegeInsert     = migrate.PrivilegeInsert
	PrivilegeUpdate     = migrate.PrivilegeUpdate
	PrivilegeDelete     = migrate.PrivilegeDelete
	PrivilegeTruncate   = migrate.PrivilegeTruncate
	PrivilegeReferences = migrate.PrivilegeReferences
	PrivilegeTrigger    = migrate.PrivilegeTrigger
)

The table privileges AssertPrivileges accepts.

View Source
const (
	// DefaultVersionTable is the unqualified name of the version table
	// inside the caller's schema in legacy mode.
	DefaultVersionTable = migrate.DefaultVersionTable
	// DefaultLedgerSchema is the schema holding the shared ledger table.
	DefaultLedgerSchema = migrate.DefaultLedgerSchema
	// DefaultSharedVersionTable is the unqualified name of the shared table
	// inside DefaultLedgerSchema.
	DefaultSharedVersionTable = migrate.DefaultSharedVersionTable
	// DefaultLockPollSeconds and DefaultLockMaxRetries bound the wait for
	// the advisory lock: both extracted implementations chose these.
	DefaultLockPollSeconds = migrate.DefaultLockPollSeconds
	DefaultLockMaxRetries  = migrate.DefaultLockMaxRetries
)

Defaults a Config leaves to this module.

Variables

View Source
var (
	// ErrInvalidConfig means the module was wired up wrongly and retrying
	// will not help. See domain.ErrInvalidConfig.
	ErrInvalidConfig = domain.ErrInvalidConfig
	// ErrUnavailable means the database was not reachable or not usable
	// just now, and a retry is worth making. See domain.ErrUnavailable.
	ErrUnavailable = domain.ErrUnavailable
)

The module's error taxonomy: two sentinels, split by the one question a caller can act on — retry, or fix the deployment.

Functions

func AssertPrivileges

func AssertPrivileges(ctx context.Context, tx Tx, p Privileges) error

AssertPrivileges asserts exactly the grant set p describes. See migrate.AssertPrivileges.

func EnsureRole

func EnsureRole(ctx context.Context, tx Tx, role string) error

EnsureRole ensures a NOLOGIN role with no cluster-wide attributes exists. See migrate.EnsureRole.

func ExecIdempotent

func ExecIdempotent(ctx context.Context, tx Tx, stmt string) error

ExecIdempotent runs a CREATE inside a savepoint, treating a duplicate-object error as success. See migrate.ExecIdempotent.

func IsPlainIdentifier

func IsPlainIdentifier(s string) bool

IsPlainIdentifier reports whether s is safe to use as a SQL identifier. See migrate.IsPlainIdentifier.

func LockKey

func LockKey(identity string) int64

LockKey returns the advisory lock key derived from a module identity: the CRC32 (IEEE) checksum of it. See migrate.LockKey.

func Up

func Up(ctx context.Context, db DB, cfg Config) error

Up applies cfg to db: the caller's embedded migrations, then the caller's reconcilers. See migrate.Up.

Types

type Applied

type Applied = migrate.Applied

Applied describes one migration's state as the version table knows it. See migrate.Applied.

func Status

func Status(ctx context.Context, db DB, cfg Config) ([]Applied, error)

Status reports the state of every migration embedded in cfg.Migrations. See migrate.Status.

type Config

type Config = migrate.Config

Config is everything a caller supplies: its schema, its module identity, its embedded migration FS and its reconcilers. See migrate.Config.

type DB

type DB = migrate.DB

DB is the narrow Postgres handle Up and Status migrate through, which a *pgxpool.Pool satisfies without a wrapper. See migrate.DB.

type Privilege

type Privilege = migrate.Privilege

Privilege is one Postgres table privilege, from a closed set. See migrate.Privilege.

type Privileges

type Privileges = migrate.Privileges

Privileges is a declarative statement of what one role may do in one schema. See migrate.Privileges.

type Reconciler

type Reconciler = migrate.Reconciler

Reconciler is one caller-supplied assertion about declarative state, run inside the lock on every Up. See migrate.Reconciler for the contract it must satisfy.

type StdDBOpener

type StdDBOpener = migrate.StdDBOpener

StdDBOpener is the one method a DB that is not a *pgxpool.Pool owes goose. See migrate.StdDBOpener.

type TablePrivileges

type TablePrivileges = migrate.TablePrivileges

TablePrivileges is one table's complete privilege assertion. See migrate.TablePrivileges.

type Tx

type Tx = migrate.Tx

Tx is the transaction a Reconciler runs in. See migrate.Tx.

Directories

Path Synopsis
internal
domain
Package domain holds this module's value objects and its complete error taxonomy.
Package domain holds this module's value objects and its complete error taxonomy.
migrate
Package migrate applies a caller's embedded schema migrations into a Postgres schema that caller owns, and reconciles the declarative state migrations cannot express.
Package migrate applies a caller's embedded schema migrations into a Postgres schema that caller owns, and reconciles the declarative state migrations cannot express.
testdb
Package testdb is the harness every database-backed test in this module runs on: Start gives a test its own uniquely-named, isolated Postgres database, so tests run in parallel with no shared state and nothing to truncate between them.
Package testdb is the harness every database-backed test in this module runs on: Start gives a test its own uniquely-named, isolated Postgres database, so tests run in parallel with no shared state and nothing to truncate between them.
Package pgmigratetest is the conformance suite for pgmigrate: the authoritative description of the contract's edge-case behaviour, which neither the doc comments nor the DB interface can be.
Package pgmigratetest is the conformance suite for pgmigrate: the authoritative description of the contract's edge-case behaviour, which neither the doc comments nor the DB interface can be.

Jump to

Keyboard shortcuts

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