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 ¶
- 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.
- 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.
- 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},
})
}
}
Output:
Index ¶
- Constants
- Variables
- func AssertPrivileges(ctx context.Context, tx Tx, p Privileges) error
- func EnsureRole(ctx context.Context, tx Tx, role string) error
- func ExecIdempotent(ctx context.Context, tx Tx, stmt string) error
- func IsPlainIdentifier(s string) bool
- func LockKey(identity string) int64
- func Up(ctx context.Context, db DB, cfg Config) error
- type Applied
- type Config
- type DB
- type Privilege
- type Privileges
- type Reconciler
- type StdDBOpener
- type TablePrivileges
- type Tx
Examples ¶
Constants ¶
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.
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 // 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 ¶
var ( // ErrInvalidConfig means the module was wired up wrongly and retrying // will not help. See domain.ErrInvalidConfig. ErrInvalidConfig = domain.ErrInvalidConfig // 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 ¶
EnsureRole ensures a NOLOGIN role with no cluster-wide attributes exists. See migrate.EnsureRole.
func ExecIdempotent ¶
ExecIdempotent runs a CREATE inside a savepoint, treating a duplicate-object error as success. See migrate.ExecIdempotent.
func IsPlainIdentifier ¶
IsPlainIdentifier reports whether s is safe to use as a SQL identifier. See migrate.IsPlainIdentifier.
Types ¶
type Applied ¶
Applied describes one migration's state as the version table knows it. See migrate.Applied.
type Config ¶
Config is everything a caller supplies: its schema, its module identity, its embedded migration FS and its reconcilers. See migrate.Config.
type 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 ¶
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.
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. |