diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fd7b5e5..336063a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -12,7 +12,7 @@ jobs:
steps:
- uses: actions/checkout@v7.0.1
- - uses: jdx/mise-action@v5.2.10
+ - uses: jdx/mise-action@v5.3.0
- name: mise run check
run: mise run check
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5942571..c36cb57 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,47 @@ module only; the `postgres` and `sqlint` sub-modules each keep their own.
## [Unreleased]
+## [v0.8.0] - 2026-11-24
+
+The migrator manages database extensions: a program declares them by name, and `Up` activates
+them at the image's default version before any set and removes the ones declared removed after
+every set.
+
+### Added
+
+- `migrate.Extension` and `migrate.Options.Extensions`, the declarations: each a distinct,
+ non-empty `Name` with no version, since the version is the default the database offers, and a
+ `Removed` flag for an extension the migrator drops instead of activating. `New` refuses an
+ empty or repeated name, and any declaration on a dialect without the capability. Deleting a
+ declaration only stops the migrator from managing the extension; it is never dropped.
+- `migrate.ExtensionCatalog`, the dialect capability that returns the engine's statements as
+ text: `ExtensionState(param)`, the query that reads an extension's installed version, the
+ default version the database offers, and whether an update path leads from one to the other;
+ `ActivateExtension(name)`, the statements that create the extension and update it to its
+ default; and `RemoveExtension(name)`, the statement that drops it with `RESTRICT`.
+- `Migrator.Extensions(ctx)`, which reads an `ExtensionStatus` per declaration, in declared
+ order, on the pool and without the lock: `Name`, `Removed`, `Installed`, `Default`, and
+ `Pending`. An active declaration is pending while its extension is missing but offered, or
+ installed behind the default with an update path to it; a removed one while it is still
+ installed.
+- The extension stage in `Up` and a positive `Steps`, on the migrator or on a layer. Inside the
+ run's lock, after every set's history is checked, every active declaration is checked before
+ any is activated, and each missing or older one is activated in its own transaction, in
+ declared order, before any set, logged as `extension activated`. One already at its default
+ runs no statement.
+- Removal in `Up` alone: after every set, each removed declaration still installed is dropped
+ in its own transaction, in declared order, logged as `extension removed`. An object still
+ depending on the extension fails the run with the driver's error mapped through the dialect,
+ and a later set migration that drops the object lets the next `Up` remove it. `Steps`, `Down`,
+ `Reset`, and `Force` never remove, and `Reset` leaves every extension installed.
+- `Verify` checks every declaration before any set, without the lock, with the verdicts `Up`
+ and `Extensions` reach.
+- The error types: `ExtensionError`, naming the extension, over `ErrExtensionUnavailable` (an
+ extension the database does not offer), `ErrNoUpdatePath` (`NoUpdatePathError`, an installed
+ version with no update path to the default, naming both), or `ErrPending`
+ (`ExtensionPendingError`, a declaration the database does not match yet), or over the mapped
+ driver error of a failed activation or removal.
+
## [v0.7.0] - 2026-11-11
A transaction's configuration is the standard library's `*sql.TxOptions`, passed as a trailing
@@ -282,7 +323,8 @@ experiment's library packages.
- `sqltest`, the scripted `database/sql` driver every consumer's unit tier runs over: `Open`,
`Recorder`, `Response`, and the stub `Dialect`.
-[Unreleased]: https://github.com/standards-lab/sqlate/compare/v0.7.0...HEAD
+[Unreleased]: https://github.com/standards-lab/sqlate/compare/v0.8.0...HEAD
+[v0.8.0]: https://github.com/standards-lab/sqlate/compare/v0.7.0...v0.8.0
[v0.7.0]: https://github.com/standards-lab/sqlate/compare/v0.6.1...v0.7.0
[v0.6.1]: https://github.com/standards-lab/sqlate/compare/v0.6.0...v0.6.1
[v0.6.0]: https://github.com/standards-lab/sqlate/compare/v0.5.0...v0.6.0
diff --git a/README.md b/README.md
index fe87a3c..594c2ab 100644
--- a/README.md
+++ b/README.md
@@ -107,12 +107,13 @@ Three conventions the library keeps are stricter than a reader might expect:
- `header` reads the `--|` declaration header of a `.sql` file.
- `query` compiles authored statements against the pattern catalog and binds them to typed
values: rows, projections with request directives, and guards.
-- `migrate` versions a schema over authored SQL under the engine's lock, and replaces a
- third-party migration dependency.
+- `migrate` versions a schema over authored SQL, and reconciles the extensions an application
+ declares, under the engine's lock, and replaces a third-party migration dependency.
- `sqltest` is the scripted `database/sql` driver for hermetic tests.
- `postgres` (sub-module) is the PostgreSQL dialect: placeholders, error classification, the
- advisory lock, and the engine's native forms. Its `pgtest` package gives an integration test
- its own throwaway database, migrated or empty, dropped when the test ends.
+ advisory lock, the extension statements, and the engine's native forms. Its `pgtest` package
+ gives an integration test its own throwaway database, migrated or empty, dropped when the test
+ ends.
- `sqlint` (sub-module) is the conventions linter as a package, with the command at
`sqlint/cmd/sqlint`.
diff --git a/context/README.md b/context/README.md
index 5272235..c9a3ce2 100644
--- a/context/README.md
+++ b/context/README.md
@@ -25,8 +25,8 @@ express.
([header/doc.go](../header/doc.go)).
- **query** (built): compiles authored statements against the pattern catalog and binds them to
typed handles ([query/doc.go](../query/doc.go)).
-- **migrate** (built): versions a schema over authored SQL under the engine's lock
- ([migrate/doc.go](../migrate/doc.go)).
+- **migrate** (built): versions a schema over authored SQL, and reconciles the extensions an
+ application declares, under the engine's lock ([migrate/doc.go](../migrate/doc.go)).
- **sqltest** (built): the scripted `database/sql` driver for hermetic tests
([sqltest/doc.go](../sqltest/doc.go)).
- **postgres** (built): the PostgreSQL dialect sub-module, with `pgtest` for integration tests'
diff --git a/context/goals/v1.data.extensions.md b/context/goals/v1.data.extensions.md
index 9375c68..4011b52 100644
--- a/context/goals/v1.data.extensions.md
+++ b/context/goals/v1.data.extensions.md
@@ -6,30 +6,153 @@
## Tasks
-1. [ ] extension-stage
+1. [x] extension-stage
2. [ ] sqlint-extensions
3. [ ] pgvector-sql
4. [ ] pgvector-go
5. [ ] principles
+## Task brief · extension-stage
+
+**Problem**
+
+An application can't tell sqlate's migrator which Postgres extensions its schema needs. Today an
+extension is either installed by hand or written into an ordinary migration with up and down
+scripts. Those scripts pile up one per upgrade and have no honest down for a version that has no
+downgrade script. The goal needs the migrator to reconcile each declared extension to the version
+the image ships, ahead of every set and under the migrator's lock, so that starting replicas take
+turns activating. A typed failure must come before any set runs, and `Verify` and a status report
+must expose a mismatch, so go-database's admin service applies it unchanged.
+
+**Behaviors**
+
+1. `migrate.Options.Extensions` lists declarations in order. Each has a name and a removed flag,
+ and no version. `New` refuses an empty or duplicate name. It also refuses any declarations
+ when the dialect lacks the extension capability, and it still does no I/O.
+2. The extension capability is a new migrate interface that returns statement text, as `Catalog`
+ does. It returns:
+ - a state query bound to the extension name, giving the installed version (none when not
+ installed), the image's default version (none when the image doesn't offer the extension),
+ and whether an update path runs from the installed version to the default;
+ - the activation statements: create the extension if it doesn't exist, then update it to its
+ default;
+ - the removal statement: drop the extension if it exists, with RESTRICT.
+
+ The dialect quotes the name.
+3. `Up` checks every set's history and then the extensions. It checks every active declaration
+ before activating any of them. If an extension isn't available in the image, the run fails
+ with a typed error naming it. The run also fails if the installed version differs from the
+ default and no update path leads to the default, which covers an installed version newer than
+ the image's. That error names the extension and both versions. Either failure comes before any
+ activation and before any set.
+4. A declaration whose installed version already equals the default runs no statement, so a
+ pre-installed database passes under an unprivileged role. A missing or older extension is
+ activated, each declaration in its own transaction, in declared order, and each activation is
+ logged.
+5. A positive `Steps`, on the migrator or on a layer, runs the same check and activation after its
+ existing refusals and before applying anything. It removes nothing.
+6. After its sets, `Up` removes each removed declaration in declared order, each in its own
+ transaction, logging each drop. If a dependent object is left behind, RESTRICT fails the run
+ with the driver's error, mapped through the dialect. A removed declaration whose extension
+ isn't installed, or isn't available, is a no-op.
+7. Deleting a declaration only stops the migrator from managing it and never drops the extension.
+ `Down`, `Reset`, and `Force` skip the stage, and `Reset` leaves extensions installed.
+8. With `Unlocked`, the stage runs without the lock, as the sets do.
+9. `Verify` checks extensions before sets, on the pool and without the lock. An active
+ declaration that is missing or behind the default fails with a typed error that unwraps to
+ `ErrPending`. So does a removed declaration that is still installed. An unavailable extension,
+ or one with no update path, fails with its own class, not `ErrPending`. `Layer.Verify` and
+ `Status` stay set-only.
+10. `Migrator.Extensions(ctx)` reads each declaration's state in declared order, on the pool and
+ without the lock. Each entry reports the name, the removed flag, the installed version, the
+ image's default version, and whether the declaration is pending: missing or behind for an
+ active declaration, still installed for a removed one. An unavailable extension shows an empty
+ default version and is not an error.
+11. Every typed error names the extension. `errors.Is` classifies it as `ErrExtensionUnavailable`,
+ `ErrNoUpdatePath`, or `ErrPending`, and `errors.As` reaches the detail.
+12. `postgres.Dialect` implements the capability:
+ - the state query reads `pg_available_extensions` and `pg_extension_update_paths`;
+ - activation is `CREATE EXTENSION IF NOT EXISTS` then `ALTER EXTENSION … UPDATE`;
+ - removal is `DROP EXTENSION IF EXISTS … RESTRICT`.
+
+ It references no new migrate symbol outside integration-tagged code, so the postgres module
+ still builds against sqlate v0.7.0 when the workspace file is off.
+13. `pgtest.MigratedWith(t, env, prefix, opts, sets...)` is `Migrated` with the caller's
+ `migrate.Options`. `Migrated` becomes `MigratedWith` with empty options.
+14. The live proofs use the integration image's contrib extensions:
+ - hstore pre-installed at 1.4 makes `Verify` unwrap to `ErrPending` and `Extensions` report
+ it pending; after `Up` it is at 1.8 and `Verify` passes;
+ - a name the image lacks fails `Up` before any set and leaves no history row;
+ - a removed hstore with a dependent column fails `Up`, and once a set migration drops the
+ column the same `Up` drops hstore;
+ - `Reset` leaves hstore installed;
+ - two concurrent `Up` runs both succeed with one activation.
+15. The unit tier, over the scripted driver, covers what the image can't stage: an installed
+ version newer than the default with no update path fails before any activation and before
+ any set.
+16. The guide documents the stage, `Extensions`, the new errors, the capability, and
+ `MigratedWith`. The base changelog records v0.8.0, and postgres's changelog records its
+ additions under Unreleased.
+
+**Test seams**
+- `migrate.Migrator` over the scripted `database/sql` driver, with a test dialect that implements
+ the extension capability (behaviors 1–11 and 15).
+- `pgtest.MigratedWith` and `migrate.Migrator` against the integration PostgreSQL, under the
+ integration tag and the committed workspace (behaviors 12–14).
+
+**Slices**
+1. Upgrade sqlate: marathon (claude-plugins) 0.22.0 → 0.24.0 and jdx/mise-action v5.2.10 →
+ v5.3.0. Done when `mise run currency` exits 0 and the check passes.
+2. Declarations and the capability: the `Options.Extensions` declaration, `New`'s validation, the
+ capability interface, the extension error classes, and `Migrator.Extensions` reporting, with
+ unit tests and the guide.
+3. Activation in `Up` and positive `Steps`: check-all-then-activate, the failures before any
+ activation or set, one transaction per activation, logging, and `Unlocked`. Includes the
+ newer-than-image unit case and the guide.
+4. `Verify` reports extensions before sets: pending activation and pending removal unwrap to
+ `ErrPending`, and unavailable or no-path fail as their own classes. Unit tests and the guide.
+5. Removal at the end of `Up`, with `Down`, `Reset`, and `Force` skipping the stage. Unit tests
+ and the guide.
+6. postgres: the capability's statements with unit tests of their text, `pgtest.MigratedWith`,
+ the live proofs in behavior 14, the postgres changelog under Unreleased, the base changelog's
+ v0.8.0 entry, and the guide.
+
+**Out of scope**
+
+- No extension version declared in Go, no history table, no schema option: an extension installs
+ where the session's default schema puts it.
+- No `CASCADE` on create or drop, and no drop when a declaration is deleted.
+- Shipped sets declaring extensions.
+- pgvector, its module, the canonical image's pgvector build and its currency line, sqlint's
+ `extensions` key, and go-database's `admin.Status` field.
+- Moving postgres onto v0.8.0 and releasing `postgres/v0.9.0`, which sqlint-extensions does.
+
+**Door**
+
+One-way for the `v0.8.0` tag: once pushed, migrate's new exported API is public at that version
+(the `Options.Extensions` declaration, the capability interface, `Migrator.Extensions`, and the
+error classes). Everything else stays two-way until `postgres/v0.9.0`: postgres's capability
+methods and `pgtest.MigratedWith` merge unreleased, and so do the tests and the guide.
+
+**Release**
+
+`v0.8.0`
+
## Decisions
- plan: The image is an extension's sole version source: `postgres:19.0-alpine` with each extension
built from source, pgvector pinned by `ARG PGVECTOR_VERSION`. Rejected: pgvector/pgvector's
Debian images, PGDG on Debian, and a version declared in Go.
-- plan: Declarations live in `migrate.Options.Extensions` (name, optional removed state, no
- version); the stage runs before every set under the migrator's lock, each in its own transaction,
- in declared order. Rejected: an application-owned bottom set of up/down migrations.
-- plan: The stage reconciles against `pg_available_extensions` with no history table; a mismatch
- makes `Verify` unwrap to `ErrPending`; an unavailable version, or an installed one newer than the
- image's with no path down, fails before any set runs.
-- plan: A removed declaration runs `DROP EXTENSION IF EXISTS x RESTRICT` after the sets; deleting a
- declaration never drops; Reset leaves extensions installed.
- plan: Shipped migration sets declare no extensions; only the application does.
- plan: sqlint's `extensions` key; a listed module exports forms, or `forms = []` with a `reason`,
or is refused. No sqlint check against `Options.Extensions`.
- plan: Module paths `sqlate/postgres/pgvector` and `go-database/postgres/pgvector`; the latter uses
pgvector-go's root module over `database/sql` and depends on the former's metric table.
+- extension-stage: A removed declaration still installed is pending: `Verify` unwraps to
+ `ErrPending` and `Extensions` marks it pending, so `admin.Status` reports it not `Ready`.
+- extension-stage: Releases `v0.8.0` alone. postgres's capability and `pgtest.MigratedWith` merge
+ unreleased against v0.7.0; sqlint-extensions' upgrade slice moves postgres onto v0.8.0 and
+ releases `postgres/v0.9.0` before pgvector-sql needs it.
## Pending edits
@@ -38,3 +161,8 @@
- coordinator · `context/postgres-extensions.md`: delete it once `principles` promotes it, and
remove its `context/README.md` entry and the pointers in `data-intelligence.md` and
`migration-sets.md`.
+- coordinator · `roadmap/v1.data.extensions.toml`: sqlint-extensions' summary adds moving postgres
+ onto sqlate v0.8.0 and releasing `postgres/v0.9.0`.
+- coordinator · `context/postgres-extensions.md`: the check fails on any installed version with no
+ update path to the image's default (read through `pg_extension_update_paths`), not only a newer
+ one; a migrate dialect capability supplies the standard pair.
diff --git a/docs/features.md b/docs/features.md
index 0580b88..d206241 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -391,32 +391,34 @@ m, err := migrate.New(db, []migrate.Set{
**The migrator.** `New(db, sets, options)` validates the sets (at least one, names and history
tables distinct, and in each set versions positive and strictly increasing, names and up texts
-present) and takes the lock capability and the `Catalog` from the dialect when it has them. It
-performs no I/O. `Options` has defaults for every field: `LockName` (`migrate.
`, over the
-top set's table), `Unlocked`, and `Logger`.
+present), validates the extension declarations, and takes the lock capability, the `Catalog`,
+and the `ExtensionCatalog` from the dialect when it has them. It performs no I/O. `Options` has
+defaults for every field: `LockName` (`migrate.`, over the top set's table), `Unlocked`,
+`Logger`, and `Extensions`.
A method that names no set acts on the top set, the last one declared, so a migrator over one
set acts on that set. `Up`, `Verify`, `Reset`, and `Status` cover every set.
| Method | Sets | Effect |
|---|---|---|
-| `Up(ctx)` | every | Applies every pending migration, sets in declared order. |
+| `Up(ctx)` | every | Activates the declared extensions, applies every pending migration, sets in declared order, then removes the extensions declared removed. |
| `Down(ctx, n)` | top | Reverts the n most recently applied; a migration without down text is `ErrNoDown`. |
-| `Steps(ctx, n)` | top | Applies the next n when positive, reverts the last -n when negative; fewer remaining is not an error. |
+| `Steps(ctx, n)` | top | Applies the next n when positive, after activating the declared extensions as `Up` does but removing none, reverts the last -n when negative; fewer remaining is not an error. |
| `Force(ctx, version)` | top | Sets the history to the version as an operator override: every migration through it recorded clean, those above it removed, a dirty row cleared; nothing runs against the schema. |
-| `Reset(ctx)` | every | Reverts every set in reverse declared order and drops each set's history table once that set is reverted, so a later `Up` replays every set from zero. |
-| `Verify(ctx)` | every | Checks, without the lock, that each history is a clean, complete prefix of its set, and returns the first fault. |
+| `Reset(ctx)` | every | Reverts every set in reverse declared order and drops each set's history table once that set is reverted, so a later `Up` replays every set from zero; extensions stay installed. |
+| `Verify(ctx)` | every | Checks, without the lock, every extension declaration and then that each history is a clean, complete prefix of its set, and returns the first fault. |
| `Status(ctx)` | every | Reads, without the lock, a `SetStatus` per set: `Name`, `Table`, `Version` (the highest applied), `Latest`, `Pending`, and `Dirty`. |
| `Version(ctx)` | top | Reads the history's head: the highest applied version and whether it is dirty. |
+| `Extensions(ctx)` | none | Reads, without the lock, an `ExtensionStatus` per extension declaration, in declared order. |
| `Migrations()` | top | Returns a copy of the set's migrations. |
**Layers.** `Layers()` returns a `Layer` handle on every set in declared order, and
`Layer(name)` returns the one named, reporting whether it exists. A `Layer` has `Name`, `Table`,
`Migrations`, `Version`, `Verify`, `Status`, `Steps`, `Down`, and `Force`, each acting on that
-set alone. The ordering between sets holds for every verb that runs migrations: a revert is
-refused with `ErrAboveApplied` while a set above has applied migrations, and an apply is refused
-with `ErrBelowPending` while a set below has pending ones. The top set's `Down` and `Steps` on
-the migrator follow the same rule.
+set alone; `Layer.Verify` and `Layer.Status` read no extension. The ordering between sets holds
+for every verb that runs migrations: a revert is refused with `ErrAboveApplied` while a set above
+has applied migrations, and an apply is refused with `ErrBelowPending` while a set below has
+pending ones. The top set's `Down` and `Steps` on the migrator follow the same rule.
**The lock.** A run pins one connection, takes the dialect's named lock on it, does its work,
and releases the lock, so concurrent starters of the same program, in one process or across
@@ -452,11 +454,79 @@ name in every schema, so the `postgres` dialect implements `Catalog` itself. The
then checks the table after creating it, before reading it, and alters it in place only when
the check reports it outdated, so a current table is never rewritten.
+**Extensions.** `Options.Extensions` declares, in order, the database extensions the migrator
+manages. An `Extension` has a `Name` and a `Removed` flag and no version: the version is the
+default the database image offers. `New` refuses an empty or repeated name, and refuses any
+declaration when the dialect lacks the `ExtensionCatalog` capability. That capability returns
+the engine's statements as text, as `Catalog` does, and quotes the name itself:
+
+- `ExtensionState(param)` returns the query that reads one extension, its name bound at `param`, as
+ one row of three columns: the installed version (NULL when not installed), the default version
+ the database offers (NULL when it does not offer the extension), and whether an update path
+ leads from the installed version to the default. No row reads as neither installed nor offered.
+- `ActivateExtension(name)` returns the statements that create the extension when it does not exist
+ and then update it to its default.
+- `RemoveExtension(name)` returns the statement that drops the extension when it exists, with
+ `RESTRICT`.
+
+`Extensions(ctx)` reads each declaration's state on the pool, without the lock. Each
+`ExtensionStatus` has `Name`, `Removed`, `Installed` (empty when not installed), `Default` (empty
+when the database does not offer the extension), and `Pending`. An active declaration is pending
+while its extension is missing but offered, or installed behind the default with an update path to
+it; an extension the database does not offer, or one with no update path, is not pending. A
+removed declaration is pending while it is still installed. An extension the database does not
+offer is not an error.
+
+`Up` and a positive `Steps`, on the migrator or on a layer, activate the declarations. The stage
+runs inside the run's lock, on its pinned connection, or without the lock under `Unlocked`, as
+the sets do. It comes after every set's history is checked and after a layer's ordering refusal,
+and before any migration runs. It reads every active declaration first, skipping removed ones,
+and refuses the run, if any fails, before activating any. An extension the database does not
+offer fails with an `*ExtensionError` over `ErrExtensionUnavailable`. An installed version that
+differs from the default with no update path to it, which covers one newer than the default,
+fails with an `*ExtensionError` over a `*NoUpdatePathError` naming both versions. Once every
+declaration passes, a declaration already at the default runs no statement, so a pre-installed
+database passes under a role that cannot create extensions. Each missing or older one runs
+`ActivateExtension`'s statements in its own transaction, in declared order, and is logged
+through `Options.Logger` as `extension activated` with its name, the default version, and the
+installed version it came from. A failed activation stops the run with an `*ExtensionError` over
+the mapped driver error, leaving the activations before it in place and no set applied. `Down`,
+a negative `Steps`, `Reset`, and `Force` do not run the stage.
+
+`Up` alone removes. After every set is applied, it reads each removed declaration in declared
+order, on the same pinned connection and inside the same lock, or without the lock under
+`Unlocked`. Each one still installed runs `RemoveExtension`'s statement in its own transaction
+and is logged as `extension removed` with its name and the installed version. A removed
+declaration whose extension is not installed, whether or not the database offers it, runs no
+statement. Because the drop is `RESTRICT`, an object still depending on the extension, such as a
+column of its type, fails the run with an `*ExtensionError` naming the extension, over the
+driver's error mapped through the dialect; the sets stay applied, the drops before it stay in
+place, and no later declaration is dropped. A set migration that drops the dependent object lets
+the next `Up` remove the extension. `Steps`, positive or negative, `Down`, `Reset`, and `Force`
+never remove. Deleting a declaration only stops the migrator from managing the extension: it is
+never dropped, and an extension no declaration names runs no statement.
+
+`Verify` checks the declarations before any set, on the pool and without the lock, in declared
+order, and returns the first fault as an `*ExtensionError` naming the extension. An active
+declaration missing but offered, or installed behind its default with an update path, and a
+removed declaration still installed, are over an `*ExtensionPendingError`, so they unwrap to
+`ErrPending`. One the database does not offer is over `ErrExtensionUnavailable`, and an installed
+version with no update path to the default is over a `*NoUpdatePathError`; neither is
+`ErrPending`, since `Up` would refuse them rather than resolve them. A declaration at its default,
+and a removed one not installed, pass. Once every declaration passes, `Verify` checks the sets.
+These verdicts match `Up`'s checks and `Extensions`' `Pending`. The migrator's `Status` reads no
+extension.
+
**Errors.** `ErrNoLocker`, `ErrDirty` (`DirtyError`), `ErrPending` (`PendingError`, the
unapplied versions), `ErrUnknownVersion` (`UnknownVersionError`, an applied row the set does
not contain), `ErrNoDown`, `ErrVersionNotFound`, `ErrAboveApplied`, and `ErrBelowPending`. An
error from one set's history or migrations is a `*SetError` whose `Set` names the set; it
-unwraps to the set's own error, so `errors.Is` and `errors.As` reach the error inside it.
+unwraps to the set's own error, so `errors.Is` and `errors.As` reach the error inside it. An
+error from one extension declaration is an `*ExtensionError` whose `Extension` names the
+extension, over its class: `ErrExtensionUnavailable`, an extension the database does not offer;
+`ErrNoUpdatePath` (`NoUpdatePathError`, naming the installed and default versions), an installed
+version with no update path to the default, which covers one newer than the default; or
+`ErrPending` (`ExtensionPendingError`), a declaration the database does not match yet.
## sqltest: the scripted driver
@@ -619,6 +689,18 @@ is altered on the next `Up`, `Steps`, `Down`, `Reset`, or `Force`. The column be
`ServerVersion` returns `SELECT version()`, the statement an administrative read runs to report
the engine's version.
+`ExtensionState`, `ActivateExtension`, and `RemoveExtension` implement `migrate.ExtensionCatalog`,
+so a migrator under `postgres.Dialect{}` accepts extension declarations. `ExtensionState` reads
+`pg_available_extensions` for the name bound at `$1`: its `installed_version` and
+`default_version`, and an update-path flag, true when `pg_extension_update_paths` lists a path
+from the installed version to the default. The flag is irrelevant once the installed version is
+the default, and false when nothing is installed. An extension the server does not offer
+yields no row. `ActivateExtension` is `CREATE EXTENSION IF NOT EXISTS` and then
+`ALTER EXTENSION ... UPDATE`, so a missing extension is created at its default version and an
+older one is updated to it. `RemoveExtension` is `DROP EXTENSION IF EXISTS ... RESTRICT`, whose
+refusal while an object depends on the extension is SQLSTATE 2BP01, `sqlate.ErrDependentObjects`
+through `MapError`. Each statement quotes the name as an identifier.
+
`postgres.Patterns()` is the library's patterns with one overlaid: the keyset predicate a
cursor continues by, spelled as the row-value comparison `(a, b) > (x, y)` in place of the
standard chain of disjuncts. The engine accepts every other library pattern as written. A
@@ -633,11 +715,15 @@ The module's `sqlint.toml` exports the engine's native forms and the overlay dir
integration tier, behind the `integration` build tag, is the proofs only an engine can give:
non-transactional DDL, dirty state and repair, concurrent starters in one process and across
processes, the cancelled context, request values parsed by the engine, and both forms of a
-returning command returning the same row. For the total, they prove that a counted page
-agrees with its total when writes commit between the statement and the caller, where a count
-read as its own statement does not; that it agrees under concurrent writers; and that the
-counted page scans its base once under one window while the uncounted page keeps the key's
-index order. `mise run acceptance` runs them against a compose PostgreSQL and tears it down.
+returning command returning the same row. For extensions, they prove that an extension installed
+behind its default is pending until `Up` updates it, that an extension the image lacks refuses
+`Up` before any set, that a removal waits for a set migration to drop the column depending on
+it, that `Reset` leaves an extension installed, and that two concurrent `Up` runs activate an
+extension once. For the total, they prove that a counted page agrees with its total when writes
+commit between the statement and the caller, where a count read as its own statement does not;
+that it agrees under concurrent writers; and that the counted page scans its base once under one
+window while the uncounted page keeps the key's index order. `mise run acceptance` runs them
+against a compose PostgreSQL and tears it down.
### pgtest: a test's throwaway database
@@ -648,6 +734,9 @@ fails the test when `env` is unset. It returns a `*Database` holding a pinged po
database (`Pool`) and the admin DSN pointed at it (`DSN`), which a test hands to a process it
starts. `Migrated(t, env, prefix, sets...)` is `Create` with the `migrate.Set`s applied in order
under the PostgreSQL dialect, and `Database.Session()` wraps the pool under `Dialect`.
+`MigratedWith(t, env, prefix, opts, sets...)` is `Migrated` under the caller's
+`migrate.Options`, so a test can declare extensions, name the lock, or take the migrator's log;
+`Migrated` is `MigratedWith` under empty options.
When the test ends the pool is closed and the database dropped `WITH (FORCE)`, so a session
still open on it, such as a started process's pool, is ended rather than holding the drop back;
diff --git a/migrate/doc.go b/migrate/doc.go
index 336ecad..1b8fabd 100644
--- a/migrate/doc.go
+++ b/migrate/doc.go
@@ -29,6 +29,9 @@
//
// - [Migrator], which runs one or more sets, built by [New] with its
// [Options]
+// - [Extension], one extension declaration, [ExtensionStatus], one
+// declaration's state, and [ExtensionCatalog], the dialect capability
+// that supplies the extension statements
// - [Set], one migration layer, with [DefaultTable], the history table a
// set without one uses
// - [Migration], one schema step, and [Files], which reads the file
@@ -41,6 +44,9 @@
// - [SetError], an error naming its set, over the details [DirtyError],
// [PendingError], and [UnknownVersionError] and their classes
// [ErrDirty], [ErrPending], and [ErrUnknownVersion]
+// - [ExtensionError], an error naming its extension, over the details
+// [NoUpdatePathError] and [ExtensionPendingError] and the classes
+// [ErrExtensionUnavailable], [ErrNoUpdatePath], and [ErrPending]
// - [ErrNoLocker], [ErrNoDown], [ErrVersionNotFound], [ErrAboveApplied],
// and [ErrBelowPending], the refusals of a run, a revert, a force, and
// the layer ordering
diff --git a/migrate/errors.go b/migrate/errors.go
index 05f7533..b0a6f89 100644
--- a/migrate/errors.go
+++ b/migrate/errors.go
@@ -11,7 +11,8 @@ var (
ErrNoLocker = errors.New("migrate: dialect has no lock capability")
// ErrDirty is the class a *DirtyError unwraps to.
ErrDirty = errors.New("migrate: schema is dirty")
- // ErrPending is the class a *PendingError unwraps to.
+ // ErrPending is the class a *PendingError and an *ExtensionPendingError
+ // unwrap to.
ErrPending = errors.New("migrate: migrations pending")
// ErrUnknownVersion is the class an *UnknownVersionError unwraps to.
ErrUnknownVersion = errors.New("migrate: history does not match the migration set")
@@ -25,6 +26,11 @@ var (
// ErrBelowPending reports an apply on a layer refused because a layer
// below it still has pending migrations; Up applies every layer in order.
ErrBelowPending = errors.New("migrate: a layer below has pending migrations")
+ // ErrExtensionUnavailable reports a declared extension the database does
+ // not offer; an *ExtensionError names it.
+ ErrExtensionUnavailable = errors.New("migrate: extension not available")
+ // ErrNoUpdatePath is the class a *NoUpdatePathError unwraps to.
+ ErrNoUpdatePath = errors.New("migrate: extension has no update path to its default version")
)
// SetError is an error from one set's history or migrations, naming the
@@ -83,3 +89,52 @@ func (e *UnknownVersionError) Error() string {
}
func (e *UnknownVersionError) Unwrap() error { return ErrUnknownVersion }
+
+// ExtensionError is an error from one extension declaration, naming the
+// extension. It unwraps to the declaration's own error, so errors.Is
+// classifies it (ErrExtensionUnavailable, ErrNoUpdatePath, ErrPending) and
+// errors.As reaches the detail (*NoUpdatePathError, *ExtensionPendingError).
+type ExtensionError struct {
+ Extension string
+ Err error
+}
+
+func (e *ExtensionError) Error() string { return fmt.Sprintf("extension %q: %v", e.Extension, e.Err) }
+
+func (e *ExtensionError) Unwrap() error { return e.Err }
+
+// NoUpdatePathError reports an installed extension version from which no
+// update path leads to the default version the database offers, which
+// covers an installed version newer than the default.
+type NoUpdatePathError struct {
+ Installed string
+ Default string
+}
+
+func (e *NoUpdatePathError) Error() string {
+ return fmt.Sprintf("%v: installed %s, default %s", ErrNoUpdatePath, e.Installed, e.Default)
+}
+
+func (e *NoUpdatePathError) Unwrap() error { return ErrNoUpdatePath }
+
+// ExtensionPendingError reports a declaration the database does not match
+// yet: an active one whose extension is missing (Installed empty) or not at
+// Default, or a Removed one whose extension is still installed.
+type ExtensionPendingError struct {
+ Removed bool
+ Installed string
+ Default string
+}
+
+func (e *ExtensionPendingError) Error() string {
+ switch {
+ case e.Removed:
+ return fmt.Sprintf("%v: removed, still installed at %s", ErrPending, e.Installed)
+ case e.Installed == "":
+ return fmt.Sprintf("%v: not installed, default %s", ErrPending, e.Default)
+ default:
+ return fmt.Sprintf("%v: installed %s, default %s", ErrPending, e.Installed, e.Default)
+ }
+}
+
+func (e *ExtensionPendingError) Unwrap() error { return ErrPending }
diff --git a/migrate/extensions.go b/migrate/extensions.go
new file mode 100644
index 0000000..45b5220
--- /dev/null
+++ b/migrate/extensions.go
@@ -0,0 +1,208 @@
+package migrate
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+)
+
+// Extension declares one database extension the migrator manages, by name
+// and without a version: the version is the one the database image offers
+// as the extension's default. Removed marks a declaration whose extension
+// the migrator drops instead of activating. Deleting a declaration only
+// stops the migrator from managing the extension; it never drops it.
+type Extension struct {
+ Name string
+ Removed bool
+}
+
+// ExtensionCatalog is the dialect capability that manages extensions: the
+// engine-specific statements the migrator runs for each Extension
+// declaration, returned as text, as Catalog's are. A dialect provides it by
+// implementing the three methods; New refuses a declaration on a dialect
+// that does not. Each method that takes a name quotes it as the engine
+// requires.
+type ExtensionCatalog interface {
+ // ExtensionState returns the query that yields one row with three
+ // columns for the extension whose name is the query's one argument,
+ // bound at param, the dialect's placeholder: the installed version
+ // (NULL when the extension is not installed), the default version the
+ // database offers (NULL when it does not offer the extension), and
+ // whether an update path leads from the installed version to the
+ // default (a boolean). No row reads as neither installed nor offered.
+ ExtensionState(param string) string
+ // ActivateExtension returns the statements, run in order, that create
+ // the extension when it does not exist and then update it to its
+ // default version.
+ ActivateExtension(name string) []string
+ // RemoveExtension returns the statement that drops the extension when
+ // it exists, refusing (RESTRICT) when an object depends on it.
+ RemoveExtension(name string) string
+}
+
+// ExtensionStatus is one declaration's state as Migrator.Extensions reads
+// it, without the lock: the declaration's name and removed flag, the
+// installed version (empty when not installed), the default version the
+// database offers (empty when it does not offer the extension), and whether
+// the declaration is pending. An active declaration is pending while its
+// extension is missing but offered, or installed behind the default with an
+// update path to it; an extension the database does not offer, or one with
+// no update path, is not pending. A removed declaration is pending while
+// its extension is still installed.
+type ExtensionStatus struct {
+ Name string
+ Removed bool
+ Installed string
+ Default string
+ Pending bool
+}
+
+type extensionState struct {
+ installed, def string
+ path bool
+}
+
+func validateExtensions(declared []Extension, catalog ExtensionCatalog) error {
+ if len(declared) > 0 && catalog == nil {
+ return errors.New("migrate: extensions declared on a dialect without the extension capability")
+ }
+ seen := map[string]bool{}
+ for _, e := range declared {
+ if e.Name == "" {
+ return errors.New("migrate: an extension has no name")
+ }
+ if seen[e.Name] {
+ return fmt.Errorf("migrate: extension %q is declared twice", e.Name)
+ }
+ seen[e.Name] = true
+ }
+ return nil
+}
+
+// Extensions reads every extension declaration's state in declared order.
+// It runs on the pool without the lock, so it never waits on a running Up.
+// An extension the database does not offer reports an empty Default and is
+// not an error.
+func (m *Migrator) Extensions(ctx context.Context) ([]ExtensionStatus, error) {
+ out := make([]ExtensionStatus, 0, len(m.opts.Extensions))
+ for _, e := range m.opts.Extensions {
+ st, err := m.extensionState(ctx, m.db, e)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, ExtensionStatus{
+ Name: e.Name,
+ Removed: e.Removed,
+ Installed: st.installed,
+ Default: st.def,
+ Pending: errors.Is(classify(e, st), ErrPending),
+ })
+ }
+ return out, nil
+}
+
+func (m *Migrator) extensionState(ctx context.Context, q querier, e Extension) (extensionState, error) {
+ var installed, def sql.NullString
+ var path sql.NullBool
+ if _, err := m.queryOne(ctx, q, m.extensionQuery, []any{e.Name}, &installed, &def, &path); err != nil {
+ return extensionState{}, &ExtensionError{Extension: e.Name, Err: err}
+ }
+ return extensionState{installed: installed.String, def: def.String, path: path.Bool}, nil
+}
+
+func classify(e Extension, st extensionState) error {
+ switch {
+ case e.Removed && st.installed != "":
+ return &ExtensionPendingError{Removed: true, Installed: st.installed, Default: st.def}
+ case e.Removed:
+ return nil
+ case st.def == "":
+ return ErrExtensionUnavailable
+ case st.installed == st.def:
+ return nil
+ case st.installed != "" && !st.path:
+ return &NoUpdatePathError{Installed: st.installed, Default: st.def}
+ }
+ return &ExtensionPendingError{Installed: st.installed, Default: st.def}
+}
+
+func (m *Migrator) verifyExtensions(ctx context.Context) error {
+ for _, e := range m.opts.Extensions {
+ st, err := m.extensionState(ctx, m.db, e)
+ if err != nil {
+ return err
+ }
+ if err := classify(e, st); err != nil {
+ return &ExtensionError{Extension: e.Name, Err: err}
+ }
+ }
+ return nil
+}
+
+func (m *Migrator) activateExtensions(ctx context.Context, conn *sql.Conn) error {
+ type activation struct {
+ e Extension
+ st extensionState
+ }
+ var due []activation
+ for _, e := range m.opts.Extensions {
+ if e.Removed {
+ continue
+ }
+ st, err := m.extensionState(ctx, conn, e)
+ if err != nil {
+ return err
+ }
+ switch err := classify(e, st); {
+ case err == nil:
+ continue
+ case !errors.Is(err, ErrPending):
+ return &ExtensionError{Extension: e.Name, Err: err}
+ }
+ due = append(due, activation{e: e, st: st})
+ }
+ for _, a := range due {
+ err := m.inTx(ctx, conn, func(tx *sql.Tx) error {
+ for _, stmt := range m.extensions.ActivateExtension(a.e.Name) {
+ if _, err := tx.ExecContext(ctx, stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return &ExtensionError{Extension: a.e.Name, Err: err}
+ }
+ if a.st.installed == "" {
+ m.log("extension activated", "extension", a.e.Name, "version", a.st.def)
+ } else {
+ m.log("extension activated", "extension", a.e.Name, "version", a.st.def, "from", a.st.installed)
+ }
+ }
+ return nil
+}
+
+func (m *Migrator) removeExtensions(ctx context.Context, conn *sql.Conn) error {
+ for _, e := range m.opts.Extensions {
+ if !e.Removed {
+ continue
+ }
+ st, err := m.extensionState(ctx, conn, e)
+ if err != nil {
+ return err
+ }
+ if classify(e, st) == nil {
+ continue
+ }
+ err = m.inTx(ctx, conn, func(tx *sql.Tx) error {
+ _, err := tx.ExecContext(ctx, m.extensions.RemoveExtension(e.Name))
+ return err
+ })
+ if err != nil {
+ return &ExtensionError{Extension: e.Name, Err: err}
+ }
+ m.log("extension removed", "extension", e.Name, "version", st.installed)
+ }
+ return nil
+}
diff --git a/migrate/extensions_test.go b/migrate/extensions_test.go
new file mode 100644
index 0000000..3ac3f35
--- /dev/null
+++ b/migrate/extensions_test.go
@@ -0,0 +1,901 @@
+package migrate_test
+
+import (
+ "bytes"
+ "context"
+ "database/sql/driver"
+ "errors"
+ "log/slog"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/standards-lab/sqlate"
+ "github.com/standards-lab/sqlate/migrate"
+ "github.com/standards-lab/sqlate/sqltest"
+)
+
+type extensionDialect struct{ lockingDialect }
+
+func (extensionDialect) ExtensionState(param string) string {
+ return "SELECT installed, default, path FROM extensions WHERE name = " + param
+}
+
+func (extensionDialect) ActivateExtension(name string) []string {
+ return []string{`CREATE EXTENSION IF NOT EXISTS "` + name + `"`, `ALTER EXTENSION "` + name + `" UPDATE`}
+}
+
+func (extensionDialect) RemoveExtension(name string) string {
+ return `DROP EXTENSION IF EXISTS "` + name + `" RESTRICT`
+}
+
+var stateCols = []string{"installed", "default", "path"}
+
+func state(installed, def driver.Value, path bool) sqltest.Response {
+ return sqltest.Response{Columns: stateCols, Rows: [][]driver.Value{{installed, def, path}}}
+}
+
+func newExtensionMigrator(t *testing.T, declared []migrate.Extension, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) {
+ t.Helper()
+ return newExtensionSets(t, []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{Extensions: declared}, responses...)
+}
+
+func newExtensionSets(t *testing.T, sets []migrate.Set, opts migrate.Options, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) {
+ t.Helper()
+ pool, rec := sqltest.Open(t, responses...)
+ m, err := migrate.New(sqlate.Wrap(pool, extensionDialect{}), sets, opts)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ return m, rec
+}
+
+func TestNew_ValidatesExtensions(t *testing.T) {
+ pool, rec := sqltest.Open(t)
+ capable := sqlate.Wrap(pool, extensionDialect{})
+ incapable := sqlate.Wrap(pool, lockingDialect{})
+ sets := []migrate.Set{{Name: "app", Migrations: set}}
+ refused := map[string][]migrate.Extension{
+ "empty name": {{Name: "hstore"}, {Name: ""}},
+ "duplicate": {{Name: "hstore"}, {Name: "citext"}, {Name: "hstore"}},
+ "removed reused": {{Name: "hstore"}, {Name: "hstore", Removed: true}},
+ }
+ for name, declared := range refused {
+ if _, err := migrate.New(capable, sets, migrate.Options{Extensions: declared}); err == nil {
+ t.Errorf("%s: New accepted the declarations", name)
+ }
+ }
+ if _, err := migrate.New(incapable, sets, migrate.Options{Extensions: []migrate.Extension{{Name: "hstore"}}}); err == nil {
+ t.Error("New accepted a declaration on a dialect without the extension capability")
+ }
+ if _, err := migrate.New(incapable, sets, migrate.Options{}); err != nil {
+ t.Errorf("New refused no declarations on a dialect without the capability: %v", err)
+ }
+ if _, err := migrate.New(capable, sets, migrate.Options{Extensions: []migrate.Extension{{Name: "hstore"}, {Name: "citext", Removed: true}}}); err != nil {
+ t.Errorf("New refused distinct declarations: %v", err)
+ }
+ if calls := rec.Calls(); len(calls) != 0 {
+ t.Errorf("New performed I/O: %v", calls)
+ }
+}
+
+func TestExtensions_ReportsEachDeclarationInOrderOnThePool(t *testing.T) {
+ declared := []migrate.Extension{
+ {Name: "hstore"},
+ {Name: "citext"},
+ {Name: "pg_trgm"},
+ {Name: "absent"},
+ {Name: "newer"},
+ {Name: "stranded"},
+ {Name: "old", Removed: true},
+ {Name: "gone", Removed: true},
+ {Name: "orphan", Removed: true},
+ }
+ m, rec := newExtensionMigrator(t, declared,
+ state("1.4", "1.8", true),
+ state("1.6", "1.6", false),
+ state(nil, "1.6", false),
+ state(nil, nil, false),
+ state("2.0", "1.8", false),
+ state("1.1", "1.8", false),
+ state("1.0", "1.0", false),
+ state(nil, "1.2", false),
+ state("0.9", nil, false),
+ )
+ got, err := m.Extensions(context.Background())
+ if err != nil {
+ t.Fatalf("Extensions: %v", err)
+ }
+ want := []migrate.ExtensionStatus{
+ {Name: "hstore", Installed: "1.4", Default: "1.8", Pending: true},
+ {Name: "citext", Installed: "1.6", Default: "1.6"},
+ {Name: "pg_trgm", Default: "1.6", Pending: true},
+ {Name: "absent"},
+ {Name: "newer", Installed: "2.0", Default: "1.8"},
+ {Name: "stranded", Installed: "1.1", Default: "1.8"},
+ {Name: "old", Removed: true, Installed: "1.0", Default: "1.0", Pending: true},
+ {Name: "gone", Removed: true, Default: "1.2"},
+ {Name: "orphan", Removed: true, Installed: "0.9", Pending: true},
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("Extensions =\n%+v\nwant\n%+v", got, want)
+ }
+ assertOps(t, rec, slices.Repeat([]sqltest.Op{sqltest.OpQuery}, len(declared))...)
+ query := extensionDialect{}.ExtensionState("$1")
+ for i, c := range rec.Calls() {
+ if c.SQL != query || len(c.Args) != 1 || c.Args[0] != declared[i].Name {
+ t.Errorf("call %d = %+v, want the state query bound to %q", i, c, declared[i].Name)
+ }
+ }
+}
+
+func TestExtensions_NoRowReadsAsNeitherInstalledNorOffered(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore"}, {Name: "citext", Removed: true}},
+ sqltest.Response{Columns: stateCols},
+ sqltest.Response{Columns: stateCols},
+ )
+ got, err := m.Extensions(context.Background())
+ if err != nil {
+ t.Fatalf("Extensions: %v", err)
+ }
+ want := []migrate.ExtensionStatus{
+ {Name: "hstore"},
+ {Name: "citext", Removed: true},
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("Extensions = %+v, want %+v", got, want)
+ }
+ assertOps(t, rec, sqltest.OpQuery, sqltest.OpQuery)
+}
+
+func TestExtensions_NoDeclarationsReadsNothing(t *testing.T) {
+ m, rec := newExtensionMigrator(t, nil)
+ got, err := m.Extensions(context.Background())
+ if err != nil || len(got) != 0 {
+ t.Errorf("Extensions = %v, %v; want none", got, err)
+ }
+ assertOps(t, rec)
+}
+
+func TestExtensions_StateFailureNamesTheExtension(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore"}, {Name: "citext"}},
+ state("1.8", "1.8", false),
+ failed,
+ )
+ got, err := m.Extensions(context.Background())
+ if got != nil {
+ t.Errorf("Extensions returned %+v alongside its error", got)
+ }
+ if !errors.Is(err, errDriver) {
+ t.Fatalf("Extensions = %v, want the engine error", err)
+ }
+ if _, ok := errors.AsType[*sqltest.MappedError](err); !ok {
+ t.Error("engine error did not cross the mapping boundary")
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "citext" {
+ t.Errorf("Extensions = %v, want an *ExtensionError naming citext", err)
+ }
+ assertOps(t, rec, sqltest.OpQuery, sqltest.OpQuery)
+}
+
+func TestExtensionError_ClassifiesAndReachesTheDetail(t *testing.T) {
+ unavailable := error(&migrate.ExtensionError{Extension: "vector", Err: migrate.ErrExtensionUnavailable})
+ noPath := error(&migrate.ExtensionError{Extension: "hstore", Err: &migrate.NoUpdatePathError{Installed: "2.0", Default: "1.8"}})
+ pending := error(&migrate.ExtensionError{Extension: "citext", Err: &migrate.ExtensionPendingError{Installed: "1.4", Default: "1.6"}})
+ classes := []error{migrate.ErrExtensionUnavailable, migrate.ErrNoUpdatePath, migrate.ErrPending}
+ for i, err := range []error{unavailable, noPath, pending} {
+ for j, class := range classes {
+ if got := errors.Is(err, class); got != (i == j) {
+ t.Errorf("errors.Is(%v, %v) = %v", err, class, got)
+ }
+ }
+ }
+ if e, ok := errors.AsType[*migrate.NoUpdatePathError](noPath); !ok || e.Installed != "2.0" || e.Default != "1.8" {
+ t.Errorf("no-path detail = %+v, %v", e, ok)
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionPendingError](pending); !ok || e.Installed != "1.4" || e.Default != "1.6" {
+ t.Errorf("pending detail = %+v, %v", e, ok)
+ }
+ for _, c := range []struct {
+ err error
+ want []string
+ }{
+ {unavailable, []string{`"vector"`}},
+ {noPath, []string{`"hstore"`, "2.0", "1.8"}},
+ {pending, []string{`"citext"`, "1.4", "1.6"}},
+ {&migrate.ExtensionError{Extension: "pg_trgm", Err: &migrate.ExtensionPendingError{Default: "1.6"}}, []string{`"pg_trgm"`, "not installed", "1.6"}},
+ {&migrate.ExtensionError{Extension: "old", Err: &migrate.ExtensionPendingError{Removed: true, Installed: "1.0"}}, []string{`"old"`, "removed", "1.0"}},
+ } {
+ for _, w := range c.want {
+ if !strings.Contains(c.err.Error(), w) {
+ t.Errorf("%q does not name %s", c.err.Error(), w)
+ }
+ }
+ }
+}
+
+var (
+ stateQuery = extensionDialect{}.ExtensionState("$1")
+ allApplied = history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false})
+)
+
+func trace(calls []sqltest.Call) []string {
+ out := make([]string, len(calls))
+ for i, c := range calls {
+ out[i] = string(c.Op) + " " + c.SQL
+ }
+ return out
+}
+
+func activation(name string) []string {
+ out := []string{"begin "}
+ for _, stmt := range (extensionDialect{}).ActivateExtension(name) {
+ out = append(out, "exec "+stmt)
+ }
+ return append(out, "commit ")
+}
+
+func assertNoExtensionStatement(t *testing.T, rec *sqltest.Recorder) {
+ t.Helper()
+ for _, c := range rec.Calls() {
+ if c.SQL == stateQuery || strings.Contains(c.SQL, "EXTENSION") {
+ t.Errorf("ran extension statement %q", c.SQL)
+ }
+ }
+}
+
+func TestUp_ActivatesInDeclaredOrderEachInItsOwnTransactionBeforeTheSets(t *testing.T) {
+ var logs bytes.Buffer
+ pool, rec := sqltest.Open(t,
+ locked, created, history(),
+ state("1.4", "1.8", true),
+ state("1.6", "1.6", false),
+ state(nil, "1.6", false),
+ ran, ran,
+ ran, ran,
+ ran, rowWritten,
+ rowWritten, ran, rowWritten,
+ state(nil, "1.2", false),
+ unlocked,
+ )
+ m, err := migrate.New(sqlate.Wrap(pool, extensionDialect{}), []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{
+ Logger: slog.New(slog.NewTextHandler(&logs, nil)),
+ Extensions: []migrate.Extension{
+ {Name: "hstore"},
+ {Name: "citext"},
+ {Name: "old", Removed: true},
+ {Name: "pg_trgm"},
+ },
+ })
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if err := m.Up(context.Background()); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpExec,
+ sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+ calls := rec.Calls()
+ if len(calls) != 23 {
+ t.Fatalf("%d calls, want 23", len(calls))
+ }
+ for i, name := range []string{"hstore", "citext", "pg_trgm"} {
+ if c := calls[3+i]; c.SQL != stateQuery || c.Args[0] != name {
+ t.Errorf("state read %d = %+v, want %s", i, c, name)
+ }
+ }
+ want := slices.Concat(activation("hstore"), activation("pg_trgm"))
+ if got := trace(calls[6:14]); !slices.Equal(got, want) {
+ t.Errorf("activations =\n%q\nwant\n%q", got, want)
+ }
+ if calls[15].SQL != set[0].Up || calls[19].SQL != set[1].Up {
+ t.Errorf("sets ran %q and %q after the activations", calls[15].SQL, calls[19].SQL)
+ }
+ lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
+ if len(lines) != 4 {
+ t.Fatalf("log =\n%s\nwant two activations and two applies", logs.String())
+ }
+ for i, w := range [][]string{
+ {"extension activated", "extension=hstore", "version=1.8", "from=1.4"},
+ {"extension activated", "extension=pg_trgm", "version=1.6"},
+ {"migration applied", "version=1"},
+ {"migration applied", "version=2"},
+ } {
+ for _, part := range w {
+ if !strings.Contains(lines[i], part) {
+ t.Errorf("log line %d = %q, want %q", i, lines[i], part)
+ }
+ }
+ }
+ if strings.Contains(lines[1], "from=") {
+ t.Errorf("log line %q names an installed version for a missing extension", lines[1])
+ }
+}
+
+func TestUp_DeclarationsAtTheDefaultRunNoStatement(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore"}, {Name: "citext"}},
+ locked, created, allApplied,
+ state("1.8", "1.8", false),
+ state("1.6", "1.6", true),
+ unlocked,
+ )
+ if err := m.Up(context.Background()); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+}
+
+func TestApply_ChecksEveryDeclarationBeforeActivatingAnyOrApplyingASet(t *testing.T) {
+ declared := []migrate.Extension{{Name: "hstore"}, {Name: "citext"}}
+ runs := map[string]func(*migrate.Migrator) error{
+ "Up": func(m *migrate.Migrator) error { return m.Up(context.Background()) },
+ "Migrator.Steps": func(m *migrate.Migrator) error { return m.Steps(context.Background(), 1) },
+ "Layer.Steps": func(m *migrate.Migrator) error { return m.Layers()[0].Steps(context.Background(), 1) },
+ }
+ for run, fn := range runs {
+ t.Run(run+"/newer than the default", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ locked, created, history(),
+ state(nil, "1.8", false),
+ state("2.0", "1.8", false),
+ unlocked,
+ )
+ err := fn(m)
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "citext" {
+ t.Fatalf("%s = %v, want an *ExtensionError naming citext", run, err)
+ }
+ if e, ok := errors.AsType[*migrate.NoUpdatePathError](err); !ok || e.Installed != "2.0" || e.Default != "1.8" {
+ t.Errorf("%s = %v, want a *NoUpdatePathError naming 2.0 and 1.8", run, err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+ })
+ t.Run(run+"/behind with no path", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ locked, created, history(),
+ state("1.4", "1.8", true),
+ state("1.1", "1.6", false),
+ unlocked,
+ )
+ if e, ok := errors.AsType[*migrate.NoUpdatePathError](fn(m)); !ok || e.Installed != "1.1" || e.Default != "1.6" {
+ t.Errorf("%s = %+v, want a *NoUpdatePathError naming 1.1 and 1.6", run, e)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+ })
+ t.Run(run+"/unavailable", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ locked, created, history(),
+ state(nil, "1.8", false),
+ state(nil, nil, false),
+ unlocked,
+ )
+ err := fn(m)
+ if !errors.Is(err, migrate.ErrExtensionUnavailable) {
+ t.Fatalf("%s = %v, want ErrExtensionUnavailable", run, err)
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "citext" {
+ t.Errorf("%s = %v, want an *ExtensionError naming citext", run, err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+ })
+ }
+}
+
+func TestUp_ActivationFailureStopsBeforeTheNextDeclarationAndTheSets(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore"}, {Name: "pg_trgm"}},
+ locked, created, history(),
+ state(nil, "1.8", false),
+ state(nil, "1.6", false),
+ failed,
+ unlocked,
+ )
+ err := m.Up(context.Background())
+ if !errors.Is(err, errDriver) {
+ t.Fatalf("Up = %v, want the engine error", err)
+ }
+ if _, ok := errors.AsType[*sqltest.MappedError](err); !ok {
+ t.Error("engine error did not cross the mapping boundary")
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "hstore" {
+ t.Errorf("Up = %v, want an *ExtensionError naming hstore", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery, sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpRollback,
+ sqltest.OpQuery,
+ )
+}
+
+func TestSteps_PositiveActivatesBeforeApplying(t *testing.T) {
+ declared := []migrate.Extension{{Name: "pg_trgm"}}
+ t.Run("Migrator.Steps", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ locked, created, history(),
+ state(nil, "1.6", false),
+ ran, ran,
+ ran, rowWritten,
+ unlocked,
+ )
+ if err := m.Steps(context.Background(), 1); err != nil {
+ t.Fatalf("Steps: %v", err)
+ }
+ calls := rec.Calls()
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpQuery,
+ )
+ if len(calls) == 13 {
+ if got := trace(calls[4:8]); !slices.Equal(got, activation("pg_trgm")) {
+ t.Errorf("activation = %q", got)
+ }
+ if calls[9].SQL != set[0].Up {
+ t.Errorf("applied %q after the activation, want %q", calls[9].SQL, set[0].Up)
+ }
+ }
+ })
+ t.Run("Layer.Steps", func(t *testing.T) {
+ m, rec := newExtensionSets(t, []migrate.Set{library, app}, migrate.Options{Extensions: declared},
+ locked, created, history(), created, history(),
+ state(nil, "1.6", false),
+ ran, ran,
+ step, rowWritten,
+ unlocked,
+ )
+ lib, _ := m.Layer("lib")
+ if err := lib.Steps(context.Background(), 1); err != nil {
+ t.Fatalf("Steps: %v", err)
+ }
+ calls := rec.Calls()
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpQuery,
+ )
+ if len(calls) == 15 {
+ if got := trace(calls[6:10]); !slices.Equal(got, activation("pg_trgm")) {
+ t.Errorf("activation = %q", got)
+ }
+ if calls[11].SQL != library.Migrations[0].Up {
+ t.Errorf("applied %q after the activation, want %q", calls[11].SQL, library.Migrations[0].Up)
+ }
+ }
+ })
+ t.Run("refused below pending", func(t *testing.T) {
+ m, rec := newExtensionSets(t, []migrate.Set{library, app}, migrate.Options{Extensions: declared},
+ locked, created, history(), created, history(),
+ unlocked,
+ )
+ top, _ := m.Layer("app")
+ if err := top.Steps(context.Background(), 1); !errors.Is(err, migrate.ErrBelowPending) {
+ t.Fatalf("Steps = %v, want ErrBelowPending", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ )
+ assertNoExtensionStatement(t, rec)
+ })
+}
+
+func TestUp_UnlockedRunsTheStageWithoutTheLock(t *testing.T) {
+ m, rec := newExtensionSets(t, []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{
+ Unlocked: true,
+ Extensions: []migrate.Extension{{Name: "pg_trgm"}},
+ },
+ created, allApplied,
+ state(nil, "1.6", false),
+ ran, ran,
+ )
+ if err := m.Up(context.Background()); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ )
+ if got := trace(rec.Calls()); len(got) == 7 && !slices.Equal(got[3:], activation("pg_trgm")) {
+ t.Errorf("activation = %q", got[3:])
+ }
+}
+
+func removal(name string) []string {
+ return []string{"begin ", "exec " + extensionDialect{}.RemoveExtension(name), "commit "}
+}
+
+func TestUp_RemovesAfterEverySetInDeclaredOrderEachInItsOwnTransaction(t *testing.T) {
+ var logs bytes.Buffer
+ pool, rec := sqltest.Open(t,
+ locked, created, history(), created, history(),
+ state("1.6", "1.6", false),
+ ran, rowWritten,
+ ran, rowWritten,
+ state("1.0", "1.0", false),
+ ran,
+ state(nil, "1.2", false),
+ state(nil, nil, false),
+ state("0.9", nil, false),
+ ran,
+ unlocked,
+ )
+ m, err := migrate.New(sqlate.Wrap(pool, extensionDialect{}), []migrate.Set{library, app}, migrate.Options{
+ Logger: slog.New(slog.NewTextHandler(&logs, nil)),
+ Extensions: []migrate.Extension{
+ {Name: "old", Removed: true},
+ {Name: "pg_trgm"},
+ {Name: "gone", Removed: true},
+ {Name: "absent", Removed: true},
+ {Name: "orphan", Removed: true},
+ },
+ })
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if err := m.Up(context.Background()); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ calls := rec.Calls()
+ if len(calls) != 25 {
+ t.Fatalf("%d calls, want 25:\n%q", len(calls), trace(calls))
+ }
+ want := slices.Concat(
+ []string{
+ "exec SELECT lock($1)",
+ "exec " + calls[1].SQL, "query " + calls[2].SQL,
+ "exec " + calls[3].SQL, "query " + calls[4].SQL,
+ "query " + stateQuery,
+ "begin ", "exec " + library.Migrations[0].Up, "exec " + calls[8].SQL, "commit ",
+ "begin ", "exec " + app.Migrations[0].Up, "exec " + calls[12].SQL, "commit ",
+ "query " + stateQuery,
+ },
+ removal("old"),
+ []string{"query " + stateQuery, "query " + stateQuery, "query " + stateQuery},
+ removal("orphan"),
+ []string{"query SELECT unlock($1)"},
+ )
+ if got := trace(calls); !slices.Equal(got, want) {
+ t.Fatalf("calls =\n%q\nwant\n%q", got, want)
+ }
+ for i, name := range map[int]string{5: "pg_trgm", 14: "old", 18: "gone", 19: "absent", 20: "orphan"} {
+ if calls[i].Args[0] != name {
+ t.Errorf("state read %d bound %v, want %s", i, calls[i].Args[0], name)
+ }
+ }
+ if rec.Pending() != 0 {
+ t.Errorf("%d scripted responses unconsumed", rec.Pending())
+ }
+ lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
+ if len(lines) != 4 {
+ t.Fatalf("log =\n%s\nwant two applies and two removals", logs.String())
+ }
+ for i, w := range [][]string{
+ {"migration applied", "set=lib"},
+ {"migration applied", "set=app"},
+ {"extension removed", "extension=old", "version=1.0"},
+ {"extension removed", "extension=orphan", "version=0.9"},
+ } {
+ for _, part := range w {
+ if !strings.Contains(lines[i], part) {
+ t.Errorf("log line %d = %q, want %q", i, lines[i], part)
+ }
+ }
+ }
+}
+
+func TestUp_RemovalFailureNamesTheExtensionAndStopsBeforeTheNextDrop(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore", Removed: true}, {Name: "citext", Removed: true}},
+ locked, created, allApplied,
+ state("1.8", "1.8", false),
+ failed,
+ unlocked,
+ )
+ err := m.Up(context.Background())
+ if !errors.Is(err, errDriver) {
+ t.Fatalf("Up = %v, want the engine error", err)
+ }
+ if _, ok := errors.AsType[*sqltest.MappedError](err); !ok {
+ t.Error("engine error did not cross the mapping boundary")
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "hstore" {
+ t.Errorf("Up = %v, want an *ExtensionError naming hstore", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpRollback,
+ sqltest.OpQuery,
+ )
+ if calls := rec.Calls(); len(calls) == 8 && calls[5].SQL != (extensionDialect{}).RemoveExtension("hstore") {
+ t.Errorf("drop = %q, want hstore's", calls[5].SQL)
+ }
+}
+
+func TestSteps_PositiveRemovesNothing(t *testing.T) {
+ declared := []migrate.Extension{{Name: "old", Removed: true}}
+ responses := []sqltest.Response{
+ locked, created, history(),
+ ran, rowWritten,
+ rowWritten, ran, rowWritten,
+ unlocked,
+ }
+ ops := []sqltest.Op{
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpExec,
+ sqltest.OpQuery,
+ }
+ runs := map[string]func(*migrate.Migrator) error{
+ "Migrator.Steps": func(m *migrate.Migrator) error { return m.Steps(context.Background(), len(set)) },
+ "Layer.Steps": func(m *migrate.Migrator) error { return m.Layers()[0].Steps(context.Background(), len(set)) },
+ }
+ for run, fn := range runs {
+ t.Run(run, func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared, responses...)
+ if err := fn(m); err != nil {
+ t.Fatalf("%s: %v", run, err)
+ }
+ assertOps(t, rec, ops...)
+ assertNoExtensionStatement(t, rec)
+ })
+ }
+}
+
+func TestUp_UnlockedRemovesWithoutTheLock(t *testing.T) {
+ m, rec := newExtensionSets(t, []migrate.Set{{Name: "app", Migrations: set}}, migrate.Options{
+ Unlocked: true,
+ Extensions: []migrate.Extension{{Name: "old", Removed: true}},
+ },
+ created, allApplied,
+ state("1.0", "1.0", false),
+ ran,
+ )
+ if err := m.Up(context.Background()); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ assertOps(t, rec,
+ sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpQuery,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpCommit,
+ )
+ if got := trace(rec.Calls()); len(got) == 6 && !slices.Equal(got[3:], removal("old")) {
+ t.Errorf("removal = %q", got[3:])
+ }
+ assertNoLock(t, rec)
+}
+
+func TestRevertsAndForce_RunNoExtensionStatement(t *testing.T) {
+ declared := []migrate.Extension{{Name: "pg_trgm"}, {Name: "old", Removed: true}}
+ revert := []sqltest.Op{
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpExec,
+ sqltest.OpQuery,
+ }
+ cases := []struct {
+ name string
+ run func(*migrate.Migrator) error
+ responses []sqltest.Response
+ ops []sqltest.Op
+ }{
+ {
+ "Down", func(m *migrate.Migrator) error { return m.Down(context.Background(), 1) },
+ []sqltest.Response{locked, created, allApplied, rowWritten, ran, rowWritten, unlocked},
+ revert,
+ },
+ {
+ "Steps negative", func(m *migrate.Migrator) error { return m.Steps(context.Background(), -1) },
+ []sqltest.Response{locked, created, allApplied, rowWritten, ran, rowWritten, unlocked},
+ revert,
+ },
+ {
+ "Steps zero", func(m *migrate.Migrator) error { return m.Steps(context.Background(), 0) },
+ nil,
+ nil,
+ },
+ {
+ "Reset", func(m *migrate.Migrator) error { return m.Reset(context.Background()) },
+ []sqltest.Response{locked, created, allApplied, rowWritten, ran, rowWritten, ran, rowWritten, ran, unlocked},
+ []sqltest.Op{
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery,
+ sqltest.OpExec, sqltest.OpExec, sqltest.OpExec,
+ sqltest.OpBegin, sqltest.OpExec, sqltest.OpExec, sqltest.OpCommit,
+ sqltest.OpExec,
+ sqltest.OpQuery,
+ },
+ },
+ {
+ "Force", func(m *migrate.Migrator) error { return m.Force(context.Background(), 1) },
+ []sqltest.Response{locked, created, rowWritten, rowMissing, rowWritten, unlocked},
+ []sqltest.Op{sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery},
+ },
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared, c.responses...)
+ if err := c.run(m); err != nil {
+ t.Fatalf("%s: %v", c.name, err)
+ }
+ assertOps(t, rec, c.ops...)
+ assertNoExtensionStatement(t, rec)
+ })
+ }
+}
+
+func TestVerify_ClassifiesEachExtensionFault(t *testing.T) {
+ classes := []error{migrate.ErrExtensionUnavailable, migrate.ErrNoUpdatePath, migrate.ErrPending}
+ cases := []struct {
+ name string
+ decl migrate.Extension
+ state sqltest.Response
+ class error
+ pending *migrate.ExtensionPendingError
+ noPath *migrate.NoUpdatePathError
+ }{
+ {"missing", migrate.Extension{Name: "pg_trgm"}, state(nil, "1.6", false), migrate.ErrPending, &migrate.ExtensionPendingError{Default: "1.6"}, nil},
+ {"behind", migrate.Extension{Name: "pg_trgm"}, state("1.4", "1.8", true), migrate.ErrPending, &migrate.ExtensionPendingError{Installed: "1.4", Default: "1.8"}, nil},
+ {"removed installed", migrate.Extension{Name: "old", Removed: true}, state("1.0", "1.0", false), migrate.ErrPending, &migrate.ExtensionPendingError{Removed: true, Installed: "1.0", Default: "1.0"}, nil},
+ {"removed installed, not offered", migrate.Extension{Name: "old", Removed: true}, state("0.9", nil, false), migrate.ErrPending, &migrate.ExtensionPendingError{Removed: true, Installed: "0.9"}, nil},
+ {"unavailable", migrate.Extension{Name: "vector"}, state(nil, nil, false), migrate.ErrExtensionUnavailable, nil, nil},
+ {"installed, not offered", migrate.Extension{Name: "vector"}, state("0.5", nil, false), migrate.ErrExtensionUnavailable, nil, nil},
+ {"newer than the default", migrate.Extension{Name: "hstore"}, state("2.0", "1.8", false), migrate.ErrNoUpdatePath, nil, &migrate.NoUpdatePathError{Installed: "2.0", Default: "1.8"}},
+ {"behind with no path", migrate.Extension{Name: "hstore"}, state("1.1", "1.8", false), migrate.ErrNoUpdatePath, nil, &migrate.NoUpdatePathError{Installed: "1.1", Default: "1.8"}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "citext"}, c.decl},
+ state("1.6", "1.6", false),
+ c.state,
+ )
+ err := m.Verify(context.Background())
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != c.decl.Name {
+ t.Fatalf("Verify = %v, want an *ExtensionError naming %s", err, c.decl.Name)
+ }
+ if !strings.Contains(err.Error(), `"`+c.decl.Name+`"`) {
+ t.Errorf("%q does not name %s", err.Error(), c.decl.Name)
+ }
+ for _, class := range classes {
+ if got := errors.Is(err, class); got != (class == c.class) {
+ t.Errorf("errors.Is(%v, %v) = %v", err, class, got)
+ }
+ }
+ e, ok := errors.AsType[*migrate.ExtensionPendingError](err)
+ if ok != (c.pending != nil) || ok && *e != *c.pending {
+ t.Errorf("pending detail = %+v, %v; want %+v", e, ok, c.pending)
+ }
+ n, ok := errors.AsType[*migrate.NoUpdatePathError](err)
+ if ok != (c.noPath != nil) || ok && *n != *c.noPath {
+ t.Errorf("no-path detail = %+v, %v; want %+v", n, ok, c.noPath)
+ }
+ if _, ok := errors.AsType[*migrate.SetError](err); ok {
+ t.Errorf("Verify = %v, an extension fault inside a *SetError", err)
+ }
+ assertOps(t, rec, sqltest.OpQuery, sqltest.OpQuery)
+ })
+ }
+}
+
+func TestVerify_ChecksExtensionsInDeclaredOrderOnThePoolThenTheSets(t *testing.T) {
+ declared := []migrate.Extension{{Name: "hstore"}, {Name: "gone", Removed: true}, {Name: "citext"}}
+ t.Run("passing", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ state("1.8", "1.8", false),
+ state(nil, "1.2", false),
+ state("1.6", "1.6", true),
+ exists(true), allApplied,
+ )
+ if err := m.Verify(context.Background()); err != nil {
+ t.Fatalf("Verify = %v", err)
+ }
+ assertOps(t, rec, slices.Repeat([]sqltest.Op{sqltest.OpQuery}, 5)...)
+ calls := rec.Calls()
+ for i, e := range declared {
+ if i < len(calls) && (calls[i].SQL != stateQuery || calls[i].Args[0] != e.Name) {
+ t.Errorf("call %d = %+v, want the state query bound to %q", i, calls[i], e.Name)
+ }
+ }
+ assertNoLock(t, rec)
+ })
+ t.Run("set pending after passing extensions", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ state("1.8", "1.8", false),
+ state(nil, "1.2", false),
+ state("1.6", "1.6", true),
+ exists(true), history([]driver.Value{int64(1), "a", false}),
+ )
+ err := m.Verify(context.Background())
+ if e, ok := errors.AsType[*migrate.SetError](err); !ok || e.Set != "app" || !errors.Is(err, migrate.ErrPending) {
+ t.Fatalf("Verify = %v, want a pending *SetError naming app", err)
+ }
+ if _, ok := errors.AsType[*migrate.ExtensionError](err); ok {
+ t.Errorf("Verify = %v, a set fault inside an *ExtensionError", err)
+ }
+ assertOps(t, rec, slices.Repeat([]sqltest.Op{sqltest.OpQuery}, 5)...)
+ assertNoLock(t, rec)
+ })
+ t.Run("extension fault before a pending set", func(t *testing.T) {
+ m, rec := newExtensionMigrator(t, declared,
+ state("1.8", "1.8", false),
+ state("1.0", "1.2", false),
+ exists(false),
+ )
+ err := m.Verify(context.Background())
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "gone" || !errors.Is(err, migrate.ErrPending) {
+ t.Fatalf("Verify = %v, want a pending *ExtensionError naming gone", err)
+ }
+ if _, ok := errors.AsType[*migrate.SetError](err); ok {
+ t.Errorf("Verify = %v, reported the set", err)
+ }
+ if got := len(rec.Calls()); got != 2 {
+ t.Errorf("Verify made %d calls, want the two state reads", got)
+ }
+ if err := m.Layers()[0].Verify(context.Background()); !errors.Is(err, migrate.ErrPending) {
+ t.Errorf("Layer.Verify = %v, want the set pending", err)
+ }
+ assertOps(t, rec, sqltest.OpQuery, sqltest.OpQuery, sqltest.OpQuery)
+ assertNoLock(t, rec)
+ })
+}
+
+func TestVerify_StateFailureNamesTheExtension(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "hstore"}}, failed)
+ err := m.Verify(context.Background())
+ if !errors.Is(err, errDriver) {
+ t.Fatalf("Verify = %v, want the engine error", err)
+ }
+ if e, ok := errors.AsType[*migrate.ExtensionError](err); !ok || e.Extension != "hstore" {
+ t.Errorf("Verify = %v, want an *ExtensionError naming hstore", err)
+ }
+ assertOps(t, rec, sqltest.OpQuery)
+}
+
+func TestLayerVerifyAndStatus_ReadNoExtension(t *testing.T) {
+ m, rec := newExtensionMigrator(t, []migrate.Extension{{Name: "pg_trgm"}, {Name: "old", Removed: true}},
+ exists(true), allApplied,
+ exists(true), allApplied,
+ )
+ if err := m.Layers()[0].Verify(context.Background()); err != nil {
+ t.Errorf("Layer.Verify = %v", err)
+ }
+ if _, err := m.Status(context.Background()); err != nil {
+ t.Errorf("Status = %v", err)
+ }
+ assertOps(t, rec, sqltest.OpQuery, sqltest.OpQuery, sqltest.OpQuery, sqltest.OpQuery)
+ assertNoExtensionStatement(t, rec)
+}
+
+func assertNoLock(t *testing.T, rec *sqltest.Recorder) {
+ t.Helper()
+ for _, c := range rec.Calls() {
+ if strings.Contains(c.SQL, "lock(") {
+ t.Errorf("ran lock statement %q", c.SQL)
+ }
+ }
+}
diff --git a/migrate/migrate.go b/migrate/migrate.go
index 58a07f9..c7245ab 100644
--- a/migrate/migrate.go
+++ b/migrate/migrate.go
@@ -25,9 +25,14 @@ type Options struct {
// a lock of its own around every run; concurrent starters without one
// are unsafe.
Unlocked bool
- // Logger records each applied and reverted migration, each forced
- // version, and each history table Reset drops; nil is silent.
+ // Logger records each activated and removed extension, each applied and
+ // reverted migration, each forced version, and each history table Reset
+ // drops; nil is silent.
Logger *slog.Logger
+ // Extensions declares the database extensions the migrator manages, in
+ // order, each by a distinct, non-empty name. Declaring any requires a
+ // dialect with the ExtensionCatalog capability.
+ Extensions []Extension
}
// Version is the history's head: the highest applied version and whether
@@ -42,11 +47,13 @@ type Version struct {
// connection under one lock. Its methods without a set act on the top set,
// except Up, Verify, Reset, and Status, which cover every set.
type Migrator struct {
- db *sqlate.DB
- layers []*layer
- opts Options
- locker sqlate.Locker
- after func(time.Duration) <-chan time.Time
+ db *sqlate.DB
+ layers []*layer
+ opts Options
+ locker sqlate.Locker
+ after func(time.Duration) <-chan time.Time
+ extensions ExtensionCatalog
+ extensionQuery string
}
const (
@@ -60,8 +67,11 @@ var tableName = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
// with a name no other set uses and a history table (DefaultTable when
// empty, so at most one set may leave it empty) no other set uses, and each
// set's migrations with positive, strictly increasing versions and names
-// and up texts present. The lock capability and the Catalog are taken from
-// the dialect when it has them. New performs no I/O.
+// and up texts present. Each extension declaration needs a non-empty name
+// no other declaration uses, and any declaration needs a dialect with the
+// ExtensionCatalog capability. The lock capability, the Catalog, and the
+// ExtensionCatalog are taken from the dialect when it has them. New
+// performs no I/O.
func New(db *sqlate.DB, sets []Set, opts Options) (*Migrator, error) {
if db == nil {
return nil, errors.New("migrate: nil db")
@@ -106,10 +116,27 @@ func New(db *sqlate.DB, sets []Set, opts Options) (*Migrator, error) {
sql: history(table, db.Dialect().Placeholder, catalog),
})
}
+ extensions, _ := db.Dialect().(ExtensionCatalog)
+ if err := validateExtensions(opts.Extensions, extensions); err != nil {
+ return nil, err
+ }
+ var extensionQuery string
+ if extensions != nil {
+ extensionQuery = extensions.ExtensionState(db.Dialect().Placeholder(1))
+ }
+ opts.Extensions = slices.Clone(opts.Extensions)
if opts.LockName == "" {
opts.LockName = "migrate." + layers[len(layers)-1].table
}
- return &Migrator{db: db, layers: layers, opts: opts, locker: locker, after: time.After}, nil
+ return &Migrator{
+ db: db,
+ layers: layers,
+ opts: opts,
+ locker: locker,
+ after: time.After,
+ extensions: extensions,
+ extensionQuery: extensionQuery,
+ }, nil
}
func validate(set Set) error {
@@ -159,10 +186,20 @@ func (m *Migrator) Migrations() []Migration { return m.topLayer().Migrations() }
// missing history table is the zero Version.
func (m *Migrator) Version(ctx context.Context) (Version, error) { return m.topLayer().Version(ctx) }
-// Verify checks every set in declared order, without the lock, that its
-// history is a clean, complete prefix of its migrations, and returns the
-// first fault as a *SetError naming the set.
+// Verify checks, on the pool and without the lock, every extension
+// declaration and then every set, each in declared order, and returns the
+// first fault. An extension fault is an *ExtensionError naming the
+// extension: an active declaration missing but offered, or installed behind
+// its default with an update path, and a removed declaration still
+// installed, are over an *ExtensionPendingError (ErrPending); one the
+// database does not offer is over ErrExtensionUnavailable, and an installed
+// version with no update path to the default over a *NoUpdatePathError,
+// neither of them ErrPending. A set fault is a *SetError naming the set
+// whose history is not a clean, complete prefix of its migrations.
func (m *Migrator) Verify(ctx context.Context) error {
+ if err := m.verifyExtensions(ctx); err != nil {
+ return err
+ }
for _, l := range m.layers {
if err := m.verify(ctx, l); err != nil {
return err
@@ -171,23 +208,36 @@ func (m *Migrator) Verify(ctx context.Context) error {
return nil
}
-// Up applies every pending migration of every set, sets in declared order,
-// under one lock on one connection. Every set's history is checked first,
-// so a dirty set or a history that does not match its set refuses the run
-// before any migration runs. The first failure stops the run; the sets
-// before it stay applied.
+// Up activates the declared extensions and then applies every pending
+// migration of every set, sets in declared order, under one lock on one
+// connection. Every set's history is checked first, so a dirty set or a
+// history that does not match its set refuses the run before any migration
+// runs. Every active extension declaration is checked next, before any is
+// activated: one the database does not offer refuses the run with an
+// *ExtensionError over ErrExtensionUnavailable, and an installed version
+// with no update path to the default with one over a *NoUpdatePathError.
+// Each declaration not at its default is then activated in its own
+// transaction, in declared order, before any set. After every set, each
+// removed declaration whose extension is still installed is dropped with
+// RESTRICT, in its own transaction, in declared order; a removed one not
+// installed runs no statement, and an object left depending on the
+// extension fails the run with an *ExtensionError over the mapped driver
+// error. The first failure stops the run; what ran before it stays applied.
func (m *Migrator) Up(ctx context.Context) error {
return m.locked(ctx, func(ctx context.Context, conn *sql.Conn) error {
applied, err := m.preflight(ctx, conn)
if err != nil {
return err
}
+ if err := m.activateExtensions(ctx, conn); err != nil {
+ return err
+ }
for i, l := range m.layers {
if err := m.applyPending(ctx, conn, l, applied[i], len(l.migrations)); err != nil {
return err
}
}
- return nil
+ return m.removeExtensions(ctx, conn)
})
}
@@ -197,8 +247,9 @@ func (m *Migrator) Up(ctx context.Context) error {
func (m *Migrator) Down(ctx context.Context, n int) error { return m.topLayer().Down(ctx, n) }
// Steps applies the top set's next n pending migrations when n is positive,
-// or reverts its last -n applied when negative; fewer remaining is not an
-// error.
+// after checking and activating the declared extensions as Up does but
+// removing none, or reverts its last -n applied when negative; fewer
+// remaining is not an error.
func (m *Migrator) Steps(ctx context.Context, n int) error { return m.topLayer().Steps(ctx, n) }
// Force sets the top set's history to version as an operator override.
@@ -213,7 +264,8 @@ func (m *Migrator) Force(ctx context.Context, version int) error {
// is reverted, so a set above never blocks the revert of the set it
// references. A later Up replays every set from zero. A caller that wants
// every set reverted with the tables left in place iterates Layers in
-// reverse and calls Down(ctx, len(l.Migrations())) on each.
+// reverse and calls Down(ctx, len(l.Migrations())) on each. Reset leaves
+// every extension installed.
func (m *Migrator) Reset(ctx context.Context) error {
return m.locked(ctx, func(ctx context.Context, conn *sql.Conn) error {
applied, err := m.preflight(ctx, conn)
diff --git a/migrate/sets.go b/migrate/sets.go
index a02fd45..37b313c 100644
--- a/migrate/sets.go
+++ b/migrate/sets.go
@@ -70,6 +70,7 @@ func (l Layer) Version(ctx context.Context) (Version, error) {
// complete prefix of its migrations. Every fault is a *SetError naming the
// set: a dirty row unwraps to a *DirtyError, a row the set does not carry
// to an *UnknownVersionError, and unapplied migrations to a *PendingError.
+// It reads no extension; Migrator.Verify checks them.
func (l Layer) Verify(ctx context.Context) error { return l.m.verify(ctx, l.m.layers[l.i]) }
// Status reads the set's state without the lock.
@@ -81,8 +82,10 @@ func (l Layer) Status(ctx context.Context) (SetStatus, error) {
// reverts its last -n applied when negative; fewer remaining is not an
// error, so -len(Migrations()) reverts the whole set. Every set's history
// is checked first. A positive n is refused with ErrBelowPending while a
-// layer below has pending migrations; a negative n is refused with
-// ErrAboveApplied while a layer above has applied ones.
+// layer below has pending migrations, and otherwise checks and activates
+// the declared extensions as Migrator.Up does before applying anything,
+// but removes none; a negative n is refused with ErrAboveApplied while a
+// layer above has applied ones and touches no extension.
func (l Layer) Steps(ctx context.Context, n int) error {
if n == 0 {
return nil
@@ -96,6 +99,9 @@ func (l Layer) Steps(ctx context.Context, n int) error {
if err := l.m.belowPending(applied, l.i); err != nil {
return err
}
+ if err := l.m.activateExtensions(ctx, conn); err != nil {
+ return err
+ }
return l.m.applyPending(ctx, conn, l.m.layers[l.i], applied[l.i], n)
}
if err := l.m.aboveApplied(applied, l.i); err != nil {
diff --git a/mise.toml b/mise.toml
index e56ec15..2e5802c 100644
--- a/mise.toml
+++ b/mise.toml
@@ -3,7 +3,7 @@
task.run_auto_install = false
[tools]
-"github:standards-lab/claude-plugins" = { version = "0.22.0", version_prefix = "marathon/v" }
+"github:standards-lab/claude-plugins" = { version = "0.24.0", version_prefix = "marathon/v" }
go = "1.27.4"
golangci-lint = "2.15.0"
jq = "1.8.2"
diff --git a/postgres/CHANGELOG.md b/postgres/CHANGELOG.md
index 6652593..75d5c5d 100644
--- a/postgres/CHANGELOG.md
+++ b/postgres/CHANGELOG.md
@@ -7,6 +7,21 @@ changelog covers this sub-module only; the base module keeps its own.
## [Unreleased]
+### Added
+
+- `Dialect.ExtensionState`, `Dialect.ActivateExtension`, and `Dialect.RemoveExtension`, the
+ statements of the `migrate.ExtensionCatalog` capability. The state read joins
+ `pg_available_extensions`, for the installed and default versions, to
+ `pg_extension_update_paths`, for whether a path leads from one to the other. Activation is
+ `CREATE EXTENSION IF NOT EXISTS` then `ALTER EXTENSION ... UPDATE`; removal is
+ `DROP EXTENSION IF EXISTS ... RESTRICT`. Each quotes the name as an identifier.
+- `pgtest.MigratedWith(t, env, prefix, opts, sets...)`, which is `Migrated` under the caller's
+ `migrate.Options`; `Migrated` is `MigratedWith` under empty options.
+- Live proofs of the extension stage against PostgreSQL 19: an extension installed behind its
+ default is pending until `Up` updates it, one the image lacks refuses `Up` before any set, a
+ removal waits for a set migration to drop the column depending on it, `Reset` leaves an
+ extension installed, and two concurrent `Up` runs activate an extension once.
+
## [v0.8.0] - 2026-11-17
### Added
diff --git a/postgres/dialect_test.go b/postgres/dialect_test.go
index df600eb..0046347 100644
--- a/postgres/dialect_test.go
+++ b/postgres/dialect_test.go
@@ -6,6 +6,7 @@ import (
"database/sql/driver"
"errors"
"fmt"
+ "slices"
"strings"
"testing"
"testing/fstest"
@@ -222,3 +223,25 @@ func TestTryLock_WrapsTheDriverError(t *testing.T) {
t.Errorf("TryLock = %v, %v; want false and the driver error naming the lock", got, err)
}
}
+
+func TestDialect_ActivateExtensionCreatesThenUpdatesTheQuotedName(t *testing.T) {
+ got := (postgres.Dialect{}).ActivateExtension(`hs"tore`)
+ want := []string{`CREATE EXTENSION IF NOT EXISTS "hs""tore"`, `ALTER EXTENSION "hs""tore" UPDATE`}
+ if !slices.Equal(got, want) {
+ t.Errorf("ActivateExtension = %q, want %q", got, want)
+ }
+}
+
+func TestDialect_RemoveExtensionDropsTheQuotedNameRestricted(t *testing.T) {
+ got := (postgres.Dialect{}).RemoveExtension(`hs"tore`)
+ if want := `DROP EXTENSION IF EXISTS "hs""tore" RESTRICT`; got != want {
+ t.Errorf("RemoveExtension = %q, want %q", got, want)
+ }
+}
+
+func TestDialect_ExtensionStateBindsTheNameOnceAtTheParam(t *testing.T) {
+ got := (postgres.Dialect{}).ExtensionState("$7")
+ if strings.Count(got, "$7") != 1 || strings.Count(got, "$") != 1 {
+ t.Errorf("ExtensionState = %q, want the name bound once, at $7, and no other parameter", got)
+ }
+}
diff --git a/postgres/doc.go b/postgres/doc.go
index 21f813e..b08cafa 100644
--- a/postgres/doc.go
+++ b/postgres/doc.go
@@ -7,6 +7,8 @@
// - the statement that reads the server's version
// - its spelling of the keyset predicate a cursor continues by
// - its migrate.Catalog implementation, the history protocol's engine half
+// - its migrate.ExtensionCatalog implementation, the statements that read,
+// activate, and remove an extension
//
// It is a sub-module so the driver it names, pgx, enters a consumer's build only
// through this import, made once where it opens its pool; a consumer opens
@@ -69,6 +71,17 @@
// unrelated schema would satisfy the check even though the current
// schema's own history table does not exist.
//
+// # Extensions
+//
+// [Dialect.ExtensionState], [Dialect.ActivateExtension], and
+// [Dialect.RemoveExtension] implement migrate.ExtensionCatalog. The state
+// read joins pg_available_extensions, for the installed and default
+// versions, to pg_extension_update_paths, for whether a path leads from
+// one to the other. Activation is CREATE EXTENSION IF NOT EXISTS then
+// ALTER EXTENSION UPDATE; removal is DROP EXTENSION IF EXISTS with
+// RESTRICT, refused with 2BP01 while an object depends on the extension.
+// Each statement quotes the name as an identifier.
+//
// # Native forms
//
// The sqlint.toml beside this file exports the engine's native forms: the
diff --git a/postgres/extensions.go b/postgres/extensions.go
new file mode 100644
index 0000000..7e813e8
--- /dev/null
+++ b/postgres/extensions.go
@@ -0,0 +1,36 @@
+package postgres
+
+import "github.com/jackc/pgx/v5"
+
+// ExtensionState returns the read of one extension's state from
+// pg_available_extensions, the extension's name bound at param: its
+// installed and default versions, and whether pg_extension_update_paths
+// lists a path from the installed version to the default. It yields no row
+// for an extension the server does not offer.
+func (Dialect) ExtensionState(param string) string {
+ return "SELECT a.installed_version, a.default_version, " +
+ "CASE WHEN a.installed_version IS NULL THEN FALSE " +
+ "WHEN a.installed_version = a.default_version THEN TRUE " +
+ "ELSE EXISTS (SELECT 1 FROM pg_extension_update_paths(a.name) p " +
+ "WHERE p.source = a.installed_version AND p.target = a.default_version AND p.path IS NOT NULL) END " +
+ "FROM pg_available_extensions a WHERE a.name = " + param
+}
+
+// ActivateExtension returns CREATE EXTENSION IF NOT EXISTS, which installs
+// the default version, then ALTER EXTENSION UPDATE, which moves an
+// installed extension to the default. The name is quoted as an identifier.
+func (Dialect) ActivateExtension(name string) []string {
+ ident := pgx.Identifier{name}.Sanitize()
+ return []string{
+ "CREATE EXTENSION IF NOT EXISTS " + ident,
+ "ALTER EXTENSION " + ident + " UPDATE",
+ }
+}
+
+// RemoveExtension returns DROP EXTENSION IF EXISTS with RESTRICT, which the
+// server refuses with SQLSTATE 2BP01, sqlate.ErrDependentObjects through
+// MapError, while an object depends on the extension. The name is quoted as
+// an identifier.
+func (Dialect) RemoveExtension(name string) string {
+ return "DROP EXTENSION IF EXISTS " + pgx.Identifier{name}.Sanitize() + " RESTRICT"
+}
diff --git a/postgres/extensions_live_test.go b/postgres/extensions_live_test.go
new file mode 100644
index 0000000..3b1818d
--- /dev/null
+++ b/postgres/extensions_live_test.go
@@ -0,0 +1,224 @@
+//go:build integration
+
+package postgres_test
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "log/slog"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/standards-lab/sqlate"
+ "github.com/standards-lab/sqlate/migrate"
+ "github.com/standards-lab/sqlate/postgres"
+ "github.com/standards-lab/sqlate/postgres/pgtest"
+)
+
+var _ migrate.ExtensionCatalog = postgres.Dialect{}
+
+const dsnEnv = "SQLATE_DSN"
+
+var hstore = []migrate.Extension{{Name: "hstore"}}
+
+func extensionSet(migrations ...migrate.Migration) []migrate.Set {
+ return []migrate.Set{{Name: "ext", Table: "ext_history", Migrations: migrations}}
+}
+
+var docTable = migrate.Migration{
+ Version: 1, Name: "doc",
+ Up: "CREATE TABLE doc (id integer PRIMARY KEY, attrs hstore)",
+ Down: "DROP TABLE doc", Transactional: true,
+}
+
+func installed(t testing.TB, db *sqlate.DB, name string) string {
+ t.Helper()
+ return text(t, db, "SELECT COALESCE((SELECT extversion FROM pg_extension WHERE extname = $1), '')", name)
+}
+
+func statusOf(t testing.TB, m *migrate.Migrator) migrate.ExtensionStatus {
+ t.Helper()
+ got, err := m.Extensions(context.Background())
+ if err != nil {
+ t.Fatalf("Extensions: %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Extensions = %+v, want one status", got)
+ }
+ return got[0]
+}
+
+func TestLive_ExtensionBehindTheDefaultIsPendingUntilUp(t *testing.T) {
+ ctx := context.Background()
+ d := pgtest.Create(t, dsnEnv, "ext")
+ db := d.Session()
+ if _, err := db.ExecContext(ctx, "CREATE EXTENSION hstore VERSION '1.4'"); err != nil {
+ t.Fatalf("install hstore 1.4: %v", err)
+ }
+ var logged bytes.Buffer
+ m := migratorOver(t, db, extensionSet(docTable), migrate.Options{
+ Extensions: hstore,
+ Logger: slog.New(slog.NewTextHandler(&logged, nil)),
+ })
+
+ err := m.Verify(ctx)
+ if !errors.Is(err, migrate.ErrPending) {
+ t.Fatalf("Verify with hstore at 1.4 = %v, want ErrPending", err)
+ }
+ if extErr, ok := errors.AsType[*migrate.ExtensionError](err); !ok || extErr.Extension != "hstore" {
+ t.Errorf("Verify = %v, want an *ExtensionError naming hstore", err)
+ }
+ if pending, ok := errors.AsType[*migrate.ExtensionPendingError](err); !ok || pending.Installed != "1.4" || pending.Default != "1.8" {
+ t.Errorf("Verify = %v, want an *ExtensionPendingError from 1.4 to 1.8", err)
+ }
+ want := migrate.ExtensionStatus{Name: "hstore", Installed: "1.4", Default: "1.8", Pending: true}
+ if got := statusOf(t, m); got != want {
+ t.Errorf("Extensions before Up = %+v, want %+v", got, want)
+ }
+
+ if err := m.Up(ctx); err != nil {
+ t.Fatalf("Up: %v", err)
+ }
+ if got := installed(t, db, "hstore"); got != "1.8" {
+ t.Errorf("hstore after Up is at %q, want 1.8", got)
+ }
+ want = migrate.ExtensionStatus{Name: "hstore", Installed: "1.8", Default: "1.8"}
+ if got := statusOf(t, m); got != want {
+ t.Errorf("Extensions after Up = %+v, want %+v", got, want)
+ }
+ if err := m.Verify(ctx); err != nil {
+ t.Errorf("Verify after Up: %v", err)
+ }
+ if !strings.Contains(logged.String(), `msg="extension activated" extension=hstore version=1.8 from=1.4`) {
+ t.Errorf("the log does not record the update from 1.4 to 1.8:\n%s", logged.String())
+ }
+}
+
+func TestLive_UnavailableExtensionRefusesUpBeforeAnySet(t *testing.T) {
+ ctx := context.Background()
+ d := pgtest.Create(t, dsnEnv, "ext")
+ db := d.Session()
+ m := migratorOver(t, db, extensionSet(migrate.Migration{
+ Version: 1, Name: "marker", Up: "CREATE TABLE marker (id integer)", Down: "DROP TABLE marker", Transactional: true,
+ }), migrate.Options{Extensions: []migrate.Extension{{Name: "sqlate_absent"}}})
+
+ err := m.Up(ctx)
+ if !errors.Is(err, migrate.ErrExtensionUnavailable) {
+ t.Fatalf("Up with an extension the image lacks = %v, want ErrExtensionUnavailable", err)
+ }
+ if extErr, ok := errors.AsType[*migrate.ExtensionError](err); !ok || extErr.Extension != "sqlate_absent" {
+ t.Errorf("Up = %v, want an *ExtensionError naming sqlate_absent", err)
+ }
+ if v, err := m.Version(ctx); err != nil || v != (migrate.Version{}) {
+ t.Errorf("Version after the refused Up = %+v, %v; want no history row", v, err)
+ }
+ if n := count(t, db, "SELECT COUNT(*) FROM ext_history"); n != 0 {
+ t.Errorf("history holds %d rows after the refused Up, want none", n)
+ }
+ if got := text(t, db, "SELECT COALESCE(CAST(to_regclass('marker') AS text), '')"); got != "" {
+ t.Errorf("the set's table %q exists after the refused Up", got)
+ }
+}
+
+func TestLive_RemovedExtensionWaitsForItsDependentColumn(t *testing.T) {
+ ctx := context.Background()
+ d := pgtest.MigratedWith(t, dsnEnv, "ext", migrate.Options{Extensions: hstore}, extensionSet(docTable)...)
+ db := d.Session()
+ if got := installed(t, db, "hstore"); got != "1.8" {
+ t.Fatalf("hstore after MigratedWith is at %q, want 1.8", got)
+ }
+ removed := migrate.Options{Extensions: []migrate.Extension{{Name: "hstore", Removed: true}}}
+
+ blocked := migratorOver(t, db, extensionSet(docTable), removed)
+ err := blocked.Up(ctx)
+ extErr, ok := errors.AsType[*migrate.ExtensionError](err)
+ if !ok || extErr.Extension != "hstore" {
+ t.Fatalf("Up removing hstore under a dependent column = %v, want an *ExtensionError naming hstore", err)
+ }
+ if !errors.Is(err, sqlate.ErrDependentObjects) {
+ t.Errorf("Up = %v, want it over sqlate.ErrDependentObjects", err)
+ }
+ if got := installed(t, db, "hstore"); got != "1.8" {
+ t.Errorf("hstore after the refused removal is at %q, want 1.8 still", got)
+ }
+ if got := statusOf(t, blocked); !got.Pending || !got.Removed {
+ t.Errorf("Extensions after the refused removal = %+v, want a pending removal", got)
+ }
+
+ dropColumn := migrate.Migration{
+ Version: 2, Name: "drop attrs",
+ Up: "ALTER TABLE doc DROP COLUMN attrs",
+ Down: "ALTER TABLE doc ADD COLUMN attrs hstore", Transactional: true,
+ }
+ var logged bytes.Buffer
+ removed.Logger = slog.New(slog.NewTextHandler(&logged, nil))
+ m := migratorOver(t, db, extensionSet(docTable, dropColumn), removed)
+ if err := m.Up(ctx); err != nil {
+ t.Fatalf("Up after the column's drop: %v", err)
+ }
+ if got := installed(t, db, "hstore"); got != "" {
+ t.Errorf("hstore after Up is at %q, want it dropped", got)
+ }
+ if v, err := m.Version(ctx); err != nil || v.Version != 2 {
+ t.Errorf("Version = %+v, %v; want 2", v, err)
+ }
+ if !strings.Contains(logged.String(), `msg="extension removed" extension=hstore version=1.8`) {
+ t.Errorf("the log does not record hstore's removal:\n%s", logged.String())
+ }
+ if err := m.Verify(ctx); err != nil {
+ t.Errorf("Verify after the removal: %v", err)
+ }
+}
+
+func TestLive_ResetLeavesTheExtensionInstalled(t *testing.T) {
+ ctx := context.Background()
+ opts := migrate.Options{Extensions: hstore}
+ d := pgtest.MigratedWith(t, dsnEnv, "ext", opts, extensionSet(docTable)...)
+ db := d.Session()
+ m := migratorOver(t, db, extensionSet(docTable), opts)
+ if err := m.Reset(ctx); err != nil {
+ t.Fatalf("Reset: %v", err)
+ }
+ if got := text(t, db, "SELECT COALESCE(CAST(to_regclass('doc') AS text), '')"); got != "" {
+ t.Fatalf("Reset left the set's table %q; the proof starts from the wrong state", got)
+ }
+ if got := installed(t, db, "hstore"); got != "1.8" {
+ t.Errorf("hstore after Reset is at %q, want 1.8", got)
+ }
+}
+
+func TestLive_ConcurrentUpsActivateOnce(t *testing.T) {
+ ctx := context.Background()
+ d := pgtest.Create(t, dsnEnv, "ext")
+ db := d.Session()
+ var logged bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&logged, nil))
+ opts := migrate.Options{Extensions: hstore, Logger: logger}
+ runners := []*migrate.Migrator{
+ migratorOver(t, db, extensionSet(docTable), opts),
+ migratorOver(t, db, extensionSet(docTable), opts),
+ }
+
+ errs := make([]error, len(runners))
+ var wg sync.WaitGroup
+ for i, m := range runners {
+ wg.Go(func() { errs[i] = m.Up(ctx) })
+ }
+ wg.Wait()
+ for i, err := range errs {
+ if err != nil {
+ t.Errorf("Up %d: %v", i, err)
+ }
+ }
+ if n := strings.Count(logged.String(), `msg="extension activated"`); n != 1 {
+ t.Errorf("hstore activated %d times over two concurrent runs, want once:\n%s", n, logged.String())
+ }
+ if n := strings.Count(logged.String(), `msg="migration applied"`); n != 1 {
+ t.Errorf("the set's migration applied %d times over two concurrent runs, want once:\n%s", n, logged.String())
+ }
+ if got := installed(t, db, "hstore"); got != "1.8" {
+ t.Errorf("hstore after the runs is at %q, want 1.8", got)
+ }
+}
diff --git a/postgres/pgtest/doc.go b/postgres/pgtest/doc.go
index 184a800..2abab28 100644
--- a/postgres/pgtest/doc.go
+++ b/postgres/pgtest/doc.go
@@ -12,6 +12,8 @@
// variable is unset
// - [Migrated], which is Create with migration sets applied through the
// migrate package under the PostgreSQL dialect
+// - [MigratedWith], which is Migrated with the caller's migrate.Options,
+// such as extension declarations
// - [Database.Session], which wraps the pool under postgres.Dialect
//
// It imports testing, so it belongs only in a consumer's test builds: a
diff --git a/postgres/pgtest/pgtest.go b/postgres/pgtest/pgtest.go
index f0a08dc..137da6c 100644
--- a/postgres/pgtest/pgtest.go
+++ b/postgres/pgtest/pgtest.go
@@ -48,12 +48,19 @@ func Create(t testing.TB, env, prefix string) *Database {
return &Database{Pool: pool(t, dsn), DSN: dsn}
}
-// Migrated is Create with sets applied, in order, through migrate.New and
-// Up under postgres.Dialect.
+// Migrated is MigratedWith under empty options.
func Migrated(t testing.TB, env, prefix string, sets ...migrate.Set) *Database {
+ t.Helper()
+ return MigratedWith(t, env, prefix, migrate.Options{}, sets...)
+}
+
+// MigratedWith is Create with sets applied, in order, through migrate.New
+// with opts and Up under postgres.Dialect, so a test can declare
+// extensions, name the lock, or take the migrator's log.
+func MigratedWith(t testing.TB, env, prefix string, opts migrate.Options, sets ...migrate.Set) *Database {
t.Helper()
d := Create(t, env, prefix)
- m, err := migrate.New(d.Session(), sets, migrate.Options{})
+ m, err := migrate.New(d.Session(), sets, opts)
if err != nil {
t.Fatalf("migrate.New: %v", err)
}