Documentation
¶
Overview ¶
Package migrate applies a caller's embedded schema migrations into a Postgres schema that caller owns, and reconciles the declarative state migrations cannot express. It is the only package in this module that imports goose; consumers see Up, Status, Applied, Config, DB and Reconciler through the facade.
A schema per caller, with its own version table inside it ¶
A library whose tables live in its *consumer's* database cannot use that consumer's migration sequence: two independent migration owners writing one database collide on goose's single version table. So each library owns a Postgres schema and keeps its version table inside it — Config.Schema and Config.Schema + "." + Config.VersionTable. Independent sequences, no shared ordering, no collision. A schema per library is also the unit privilege separation needs.
The schema is created by Up itself, before goose runs, rather than only by the caller's migration 00001. goose has to be able to create its bookkeeping table before any migration has run, and that table lives in the schema — so the schema has to exist first. The alternative, which one of the two extracted implementations took and which this module deliberately does not offer, is to put the version table in public, where it is immediately available and immediately shared with whatever else is migrating that database.
What Up applies, and in which of three layers ¶
Up is three things in sequence, and which layer a piece of DDL belongs in is decided by one question: can a later deployment legitimately change it?
The fixed schema, as goose migrations (Config.Migrations). Tables, the partitioning strategy, triggers, row-level security policies, indexes. Versioned, applied once, never changed. These are the decisions that cannot be revisited — converting a populated table to a partitioned one is an outage.
and 3. The declarative state, reconciled on every Up (Config.Reconcilers). Roles, grants, revokes, partition windows: anything whose correct value is a function of the configuration this deployment is running with, rather than of the order in which configurations were tried.
Layer 1 is this module's. Layers 2 and 3 are the caller's, and that split is the charter's load-bearing line: this module owns *when and how* reconciliation runs — inside the lock, in one transaction, after the versioned migrations, on every run — and knows nothing about what is being reconciled. The alternative is a module that accumulates every consumer's partitioning strategy.
Reconciling rather than migrating declarative state is not a style preference; it was discovered. A versioned migration records itself as applied, so a deployment that later renames its application role has its privilege migration silently skipped and comes up with no privilege separation at all while the migrator reports everything applied. That failure is silent, which is why it is the module's responsibility rather than each consumer's to get the phase ordering right.
The pool handed to Up is a migration pool, not the runtime pool ¶
Up's DB must connect as a role that can create objects in — and ideally owns — Config.Schema, and that can GRANT to and REVOKE from whatever roles the caller's reconcilers name. That is the owner identity, and it is deliberately not the identity the application runs as. Runtime work uses a separate pool on the application role.
The two are different credentials, not two states of one session. SET ROLE is the mechanism that looks like it would do, and it must not be used for this: it is reversible with RESET ROLE, so a single owner connection that narrows 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 the separation structural — the runtime credential does not possess the mutating rights at all, so there is nothing to forget and nothing to reset.
The migration pool is also short-lived: open it, 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.
Concurrency ¶
Up and Status are safe to call concurrently, from goroutines or from separate processes against the same database. goose's migrations are serialized by a session-level advisory lock on LockKey(Config.Identity), and the reconcile transaction takes the same key as a transaction-level lock for its own work. Calling Up against an already-current database applies nothing new, re-runs every reconciler, and returns nil.
Why there is no sqlc here ¶
CONVENTIONS.md makes sqlc the default and names one exception: SQL composed at run time. This package is entirely that exception. Every statement it issues is built from configuration — a schema name, a version table name, a role name — or reads a system catalog, which sqlc cannot resolve against a schema directory that contains no pg_catalog. There is no fixed query here for a generator to generate, and this module has no migrations of its own for one to generate against.
Index ¶
- Constants
- 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
Constants ¶
const ( DefaultLedgerSchema = "migrations" )
DefaultLedgerSchema and DefaultSharedVersionTable name the shared ledger: one table, outside every module's schema, with a row per module and version. 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.
const ( DefaultLockPollSeconds = 1 DefaultLockMaxRetries = 300 )
DefaultLockPollSeconds and DefaultLockMaxRetries bound how long Up and Status wait for the advisory lock before giving up as domain.ErrUnavailable. goose's session locker polls pg_try_advisory_lock rather than blocking, so these are the poll interval in whole seconds (1 is the library's minimum) and the number of retries after the first attempt — about five minutes.
Both extracted implementations chose 1 and 300 independently, which is why these are the defaults rather than a number this module picked.
const DefaultVersionTable = "goose_db_version"
DefaultVersionTable is the unqualified name of the table goose records applied versions in. It is goose's own default name, kept rather than renamed per consumer: the table lives inside the caller's own schema, so two consumers' version tables are already distinct objects and a distinguishing prefix would only be noise.
It is worth being explicit about what this replaces. Before this module existed, one of the two implementations put its version table in public under a hand-prefixed name (public.goose_iam_db_version) precisely to dodge the bootstrap ordering problem described on ensureSchema. That works for exactly one library and then collides with the consumer's own goose sequence, which is the thing a schema per module exists to prevent.
Variables ¶
This section is empty.
Functions ¶
func AssertPrivileges ¶
func AssertPrivileges(ctx context.Context, tx Tx, p Privileges) error
AssertPrivileges applies p: USAGE on the schema if asked, then every table's grants and revokes in order, then the revokes from PUBLIC. It is meant to be called from a Reconciler, so that it runs on every Up.
It does not create the role. A caller that wants the role created calls EnsureRole first, in the same reconciler; keeping them separate is what lets a deployment whose roles are provisioned elsewhere — by its cloud provider's IAM integration, say — assert privileges without this module trying to own role creation too.
func EnsureRole ¶
EnsureRole creates role if it does not already exist, as NOLOGIN and with nothing cluster-wide: no superuser, no createdb, no createrole, no inheritance, and explicitly NOBYPASSRLS — a role that bypasses row-level security would make a schema's policies decorative.
NOLOGIN because the role this creates is a grantee, not a connection identity: it exists so that privileges can be asserted against a name. A deployment that connects as it — which is the two-pool model this module documents, and the one it recommends — gives it LOGIN and a credential out of band, through whatever manages its secrets. Nothing here depends on which, and nothing here should: a migration that could mint a login credential would be a migration that could mint one for itself.
Roles are cluster-wide rather than per-database while the advisory lock is per-database, so two databases on one cluster can race to create the same role at the same moment. A guard that checks pg_roles first still loses that race, so the duplicate is caught rather than prevented; see ExecIdempotent.
func ExecIdempotent ¶
ExecIdempotent runs a CREATE that is meant to be a no-op when the object already exists, inside a savepoint, and treats a duplicate-object error as success.
Two things make this necessary rather than convenient, and both were found the hard way:
CREATE ... IF NOT EXISTS still loses a race against a concurrent identical statement, because both sessions can see "not there" before either commits. The advisory lock serializes one caller's migrations against another instance of the *same* caller, and roles are cluster-wide while the lock is per-database, so two test databases on one cluster race to create the same role. CREATE ROLE has no IF NOT EXISTS form at all.
In Postgres a failed statement aborts the whole transaction, so "try it and ignore the duplicate" is only available to a caller that can roll back to just before the attempt. The savepoint is the point.
It is exported because it is the plumbing every reconciler that creates anything needs, and re-deriving the savepoint discipline in each consumer is how one of them comes to poison its own transaction.
func IsPlainIdentifier ¶
IsPlainIdentifier reports whether s is safe to use as an unquoted-shaped SQL identifier: ASCII letters, digits and underscore, not starting with a digit, and not empty.
Every identifier this module interpolates is also run through pgx.Identifier.Sanitize, which quotes and escapes it. This check is a second, narrower gate in front of that, applied to the identifiers that come from configuration — and GRANT, REVOKE and CREATE ROLE cannot take a name as a bound parameter, so those names are the values that have to reach Postgres as SQL text. A value in that position gets more than one reason to be safe.
It is exported because a caller writing a reconciler is building DDL from its own configuration and needs the same gate; re-deriving it is how the two come to disagree about what is plain.
func LockKey ¶
LockKey returns the Postgres advisory lock key derived from a module identity: the CRC32 (IEEE) checksum of it, widened to int64.
LockKey("github.com/laenenai/audit/internal/migrate") == 1367485358
LockKey("github.com/laenenai/iam/internal/migrate") == 3346129644
Both extracted implementations computed exactly this, independently, and hardcoded the result as a constant. The unit test for this function pins the two values above, so that the extraction cannot silently move either consumer's lock.
CRC32 is not a security property here and does not need to be: the key only has to be stable for one identity and unlikely to equal a key some unrelated thing in the same cluster picked. A hand-chosen constant collides eventually; a checksum of the import path collides only if two import paths do.
A module path rename changes the key ¶
This is the one operational consequence of deriving the key from the import path, and it is worth knowing before a path migration rather than during one. Two builds of the same consumer either side of a rename hash two different identities, so they take two different advisory locks and do not serialize against each other — if both run against one database during a rollout, they can migrate concurrently, which is the race the lock exists to prevent.
The two examples above are themselves evidence: these keys were 1966699558 and 1000744357 while the modules lived under a "laenen-ai" path, and renaming the organisation moved both.
It is still the right trade, because the alternative is a hand-chosen constant that collides eventually and silently. A deployment renaming its module path and unwilling to accept the window pins Identity to the old path for one release — Identity is a string a caller passes, not something this module reads from the build, precisely so that it can be held still while the import path moves.
It is exported because the key is operational surface — it is what an operator sees in pg_locks while a deployment is migrating, and what a test asserts against to prove something ran inside the lock.
func Up ¶
Up applies cfg to db: the caller's embedded migrations, then the caller's reconcilers. See the package doc comment for why those are separate layers and for what db must and must not be.
Up is safe to call concurrently. Calling it against an already-current database applies nothing new, re-runs every reconciler, and returns nil.
Types ¶
type Applied ¶
type Applied struct {
// Version is the migration's leading version number, e.g. 1 for
// 00001_init.sql.
Version int64
// Name is the migration's filename, e.g. "00001_init.sql".
Name string
// Applied reports whether this migration has been applied. AppliedAt is
// the zero time when it has not.
Applied bool
AppliedAt time.Time
}
Applied describes one migration's state as goose's bookkeeping table knows it, for an operator-facing status command to print.
func Status ¶
Status reports the state of every migration embedded in cfg.Migrations: applied ones with the time they were applied, and pending ones not yet run. It takes the same advisory lock as Up for the duration of the call, so a status read reflects a consistent view rather than racing a concurrent Up.
It reports layer 1 only. Reconcilers have no "pending" state to report: they are asserted on every Up, so "is the declarative state correct" is answered by reading the database against the running configuration, never by a version number. That is the whole reason they are not versioned.
Status takes a Config where the charter's sketch took only a handle. It has to: the schema, the version table, the embedded set and the lock key are all the caller's now, and in the two implementations this module was extracted from they were compile-time constants of the caller's own package.
type Config ¶
type Config struct {
// Schema is the Postgres schema this caller owns. Up creates it before
// goose runs. In legacy mode (Module empty) the version table lives
// inside it, so two consumers of one database never share a version
// table. In shared mode it is only the module's own schema; the ledger
// lives in LedgerSchema.
//
// Required, and it must be a plain identifier: letters, digits and
// underscore, not starting with a digit. There is no default, because a
// default would be a schema name nobody chose.
Schema string
// Module enables the shared ledger and names this caller's rows in it.
// Empty keeps the legacy per-schema goose_db_version, so existing
// consumers do not change. It must be a plain identifier.
//
// The ledger is per database. A module pointed at another database gets
// that database's ledger; its module name does not change.
Module string
// LedgerSchema is the schema holding the shared table. Zero means
// DefaultLedgerSchema. Only meaningful with Module, and validated only
// then.
LedgerSchema string
// Identity is the import path of the package that owns Migrations —
// "github.com/laenenai/example/internal/migrate", say. The advisory lock
// key is the CRC32 (IEEE) checksum of it; see LockKey.
//
// It is an input rather than a constant in this module because the
// identity being hashed is the *caller's*, not this module's: two
// consumers migrating two schemas in one database have no reason to wait
// for each other, and a key derived from pgmigrate's own import path
// would make them.
//
// Required. Whatever a caller passes, it must never change: changing it
// would let an old and a new binary migrate concurrently against each
// other during a rolling deploy, which is the race the lock exists to
// prevent. It is a string a caller passes rather than something read
// out of the build so that it can be held still across a module path
// rename; see LockKey.
Identity string
// Migrations is the caller's embedded goose migration set — an
// embed.FS whose root holds NNNNN_name.sql files. Required.
//
// Embedded rather than read from disk because the deployment model this
// module serves is a single binary that migrates itself at startup: a
// library whose tables live in its consumer's database cannot ask that
// consumer to run a migration tool.
Migrations fs.FS
// Reconcilers are the caller's declarative assertions, run inside the
// lock, in one transaction, after the versioned migrations, on every
// Up. This module owns when and how they run and knows nothing about
// what they reconcile. Optional: a caller with no declarative state
// passes none and no reconcile transaction is opened.
//
// See Reconciler for the contract, and the package doc comment for why
// declarative state must not be a versioned migration.
Reconcilers []Reconciler
// VersionTable is the unqualified name of goose's bookkeeping table
// inside Schema. Zero means DefaultVersionTable. A deployment adopting
// this module over an existing goose sequence sets it to the name that
// sequence already uses.
VersionTable string
// LockPollSeconds and LockMaxRetries bound the wait for the advisory
// lock. Zero means DefaultLockPollSeconds / DefaultLockMaxRetries; a
// negative value is a configuration error. One second is goose's
// minimum poll interval.
//
// These are configuration rather than package-level variables with a
// test hook, which is how one of the two extracted implementations
// reached the timeout path. A conformance suite has to be able to make
// that path happen in a second, from another module, through the public
// surface.
LockPollSeconds int
LockMaxRetries int
}
Config is everything a caller supplies to Up and Status. Schema, Identity and Migrations are required; the rest has a default a deployment has no reason to change unless it has a reason.
type DB ¶
type DB interface {
// Exec runs one statement. Up uses it for exactly one thing: creating
// the schema before goose runs. See ensureSchema.
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
// Begin starts the transaction the reconcile phase runs in, which is
// also the transaction that holds the advisory lock while it does.
Begin(ctx context.Context) (pgx.Tx, error)
}
DB is the narrow Postgres handle Up and Status migrate through: the two methods this module uses, and nothing else.
It is an interface rather than a *pgxpool.Pool so that a consumer which manages connections some other way — a tenancy control-plane handle, a single *pgx.Conn in a test, a transaction a caller already holds — can be migrated without this module acquiring a dependency on whatever is managing them. *pgxpool.Pool, *pgx.Conn and pgx.Tx all satisfy it as declared, with no wrapper at the call site.
The methods are pgx-shaped because goose's Postgres dialect is, and because a module that applies DDL and hands a transaction to a caller-supplied reconciler has no way to be driver-agnostic that is worth the indirection. What this interface buys is independence from a *connection manager*, which is the dependency that would otherwise travel with it.
type Privilege ¶
type Privilege string
Privilege is one Postgres table privilege. The set is closed on purpose: a privilege word reaches Postgres as SQL text, because GRANT cannot take one as a bound parameter, so the only values that can appear there are the ones named here.
const ( PrivilegeSelect Privilege = "SELECT" PrivilegeInsert Privilege = "INSERT" PrivilegeUpdate Privilege = "UPDATE" PrivilegeDelete Privilege = "DELETE" PrivilegeTruncate Privilege = "TRUNCATE" PrivilegeReferences Privilege = "REFERENCES" PrivilegeTrigger Privilege = "TRIGGER" )
The table privileges Postgres defines. MAINTAIN (Postgres 17 and later) is deliberately absent: nothing has needed it, and a closed set earns its keep by being added to on purpose.
type Privileges ¶
type Privileges struct {
// Schema is the schema the tables live in. Required, and a plain
// identifier.
Schema string
// Role is the role the privileges are asserted for. Required, and a
// plain identifier — see IsPlainIdentifier for why this one in
// particular is checked twice.
Role string
// SchemaUsage grants USAGE on Schema to Role. Without it every table
// privilege below is unreachable, so it is the usual answer; a caller
// asserting privileges in a schema some other grant already covers
// leaves it false.
SchemaUsage bool
// Tables are the per-table assertions, applied in order.
Tables []TablePrivileges
// RevokeFromPublic additionally revokes ALL on the schema and on every
// named table from PUBLIC.
//
// PUBLIC holds no table privileges by default, but "by default" is a
// property of how a table was created rather than a guarantee about how
// it is now, and a privilege held by PUBLIC would make every revoke
// above it decorative.
RevokeFromPublic bool
}
Privileges is a complete, declarative statement of what one role may do in one schema, for AssertPrivileges to assert on every Up.
It is one value in one place so that "what can this role do here" is answerable by reading a literal rather than by auditing a schema.
type Reconciler ¶
type Reconciler struct {
// Name identifies this reconciler in the error Up returns when it
// fails. Required: an unattributable failure in a caller-supplied phase
// is the one thing a generic machine cannot diagnose for the caller.
Name string
// Reconcile asserts the state. Required.
Reconcile func(ctx context.Context, tx Tx) error
}
Reconciler is one caller-supplied assertion about declarative state, run inside the advisory lock, after the versioned migrations, on every Up.
The contract a reconciler must satisfy:
It must be idempotent. It runs on every Up, including the thousandth Up against an unchanged database, and that is the point: the state of the database is then a function of the configuration the deployment is running with rather than of the order in which configurations were tried. GRANT, REVOKE and CREATE ... IF NOT EXISTS are idempotent already; see ExecIdempotent for the case they do not cover.
It must do all its work through tx, and must not commit or roll it back. Every reconciler in one Up shares one transaction, so a failure anywhere leaves the database exactly as the migrations left it rather than half-reconciled. Postgres makes DDL transactional, which is what makes that possible.
It may assume the versioned migrations have been applied, because they have; reconcilers run after them, which is why a reconciler can name a table a migration created.
It may return its own error type or sentinel. Up wraps a reconciler's error with %w and adds no sentinel of its own, so errors.Is against the caller's own sentinel still matches at the call site. A reconciler that refuses a configuration — an attempt to change a hash modulus that is fixed at creation, say — is the caller's judgement to express and this module's job to deliver intact.
type StdDBOpener ¶
StdDBOpener is the one thing goose needs that pgx's own interfaces cannot express: a database/sql handle. goose.NewProvider takes a *sql.DB, checks out exactly one *sql.Conn from it per call, and runs the session lock, the bookkeeping check and every migration statement on that one connection — which is what makes a session-scoped advisory lock actually serialize the work it is held around.
A DB that is a *pgxpool.Pool needs no help: pgx ships stdlib.OpenDBFromPool for exactly this, and Up uses it. Any other DB implementation says how to produce a database/sql handle over the same database by implementing this interface. The returned release function is called when the migration finishes, and must not close the underlying handle the caller owns — stdlib.OpenDBFromPool documents that closing the *sql.DB it returns never closes the pool behind it, and an implementation of this method is expected to preserve that property.
type TablePrivileges ¶
type TablePrivileges struct {
// Table is the table's unqualified name, inside Privileges.Schema. It
// must be a plain identifier.
Table string
// Grant is granted to the role. Revoke is revoked from it. A privilege
// in neither list is left alone, which is the one place this assertion
// is not total — Postgres offers no "revoke everything except these"
// that does not also revoke what was just granted, so a caller that
// wants a privilege definitely absent names it in Revoke.
Grant []Privilege
Revoke []Privilege
}
TablePrivileges is the complete assertion for one table: what the role holds, and what it must not.