Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
c6ee793
Fire the event trigger for DROP SCHEMA and DROP OWNED
jnasbyupgrade Sep 29, 2026
49a778f
Return early from the event trigger unless an extension was dropped
jnasbyupgrade Sep 29, 2026
e26c902
Comment why the trigger's row variable is a record
jnasbyupgrade Sep 29, 2026
c485e09
Merge branch 'master' into when-tag
jnasbyupgrade Oct 30, 2026
df5aa13
Explain why the trigger's row variable is a record
jnasbyupgrade Oct 30, 2026
0cae837
Use a block comment for the record-variable note
jnasbyupgrade Oct 30, 2026
823be14
Consolidate test plan() arithmetic; drop the database CREATE grant fr…
jnasbyupgrade Oct 30, 2026
50bf9be
Label each test plan() term with its source, one line per helper
jnasbyupgrade Oct 30, 2026
42f2d5a
Merge branch 'master' into when-tag
jnasbyupgrade Oct 30, 2026
6b689ff
Raise an actionable error when the caller can't use extension_drop__c…
jnasbyupgrade Oct 30, 2026
6628ab1
Trap the privilege error instead of pre-checking the catalog
jnasbyupgrade Oct 30, 2026
4c5460c
Tighten privilege-error docs; test the HINT's grants and a group role
jnasbyupgrade Oct 30, 2026
fc01223
Use block comments where the SQL linter requires them
jnasbyupgrade Oct 30, 2026
d5906b7
Let unregistered extensions drop without access to extension_drop__co…
jnasbyupgrade Oct 30, 2026
5c91fa9
Name the table, owner and extensions in the privilege error; test rev…
jnasbyupgrade Oct 30, 2026
5cc5569
Make the registration helper immune to a writable extension schema
jnasbyupgrade Oct 31, 2026
7ecfe1b
Require PUBLIC USAGE on the schema, pin function search_path to pg_ca…
jnasbyupgrade Nov 2, 2026
d551a00
Test the pin with operators on the compared types, document the regis…
jnasbyupgrade Nov 2, 2026
3370ef6
Reword the registered-SQL path notes in HISTORY and README
jnasbyupgrade Nov 2, 2026
d9468ca
Guard reports the missing USAGE as a state with the fixing GRANT; doc…
jnasbyupgrade Nov 2, 2026
a3b1669
Fold the XD001 text into sanity_assert and have registered() call it;…
jnasbyupgrade Nov 3, 2026
1fac7dc
Pass NULL::name to sanity_assert so a planted zero-argument overload …
jnasbyupgrade Nov 3, 2026
31eae19
Test the sanity_assert overload in its own session so every call site…
jnasbyupgrade Nov 3, 2026
1e4fe95
Address review: reuse create_function in the update script, rename th…
jnasbyupgrade Nov 3, 2026
e9a8c74
Check PUBLIC's USAGE before REVOKE/DROP OWNED too; drop redundant pg_…
jnasbyupgrade Nov 3, 2026
de11825
Drop the table-grant HINT; single finish assertion in every mode; tig…
jnasbyupgrade Nov 3, 2026
d331a27
Fix update-script header, test label and README wrapping; tighten sea…
jnasbyupgrade Nov 3, 2026
916b881
Claim registrations through a SECURITY DEFINER function
jnasbyupgrade Nov 3, 2026
04d8612
Run registered SQL in extension-name order; test multi-extension drop…
jnasbyupgrade Nov 3, 2026
a07d3f9
Tighten ORDER BY comment, banner boxes, drop_denied header and README…
jnasbyupgrade Nov 3, 2026
62d13e8
Fix extension_drop__update()/remove() touching every row; stable erro…
jnasbyupgrade Nov 3, 2026
13070a6
Run registered SQL under pg_catalog, pg_temp; drop all ORDER BYs; tig…
jnasbyupgrade Nov 3, 2026
ec2975c
Qualify test extensions' registered SQL; one row shape in drop_multip…
jnasbyupgrade Nov 3, 2026
a54e66f
Reset search_path before each registered statement
jnasbyupgrade Nov 3, 2026
4384701
Clarify the search_path reset comment
jnasbyupgrade Nov 3, 2026
d5cc8e7
Document the search_path rule where registrants look; fix CLAUDE.md
jnasbyupgrade Nov 3, 2026
5ff30c3
README: fix extension_drop schema lookup recipe (use %s, show format …
jnasbyupgrade Nov 3, 2026
76900c2
Docs: show \gexec in lookup recipe; clarify CLAUDE.md antecedent
jnasbyupgrade Nov 3, 2026
dc5437d
CLAUDE.md: rewrap
jnasbyupgrade Nov 3, 2026
6f32acd
README: show lookup recipe in registration context; name the guard tr…
jnasbyupgrade Nov 3, 2026
931c5a3
Tests: fold single-purpose suites into simple and drop_denied; shared…
jnasbyupgrade Nov 3, 2026
7c4422f
Tests: check SECURITY DEFINER over every member function; tidy commen…
jnasbyupgrade Nov 3, 2026
e0ee977
Tests: state the definer check's contract precisely
jnasbyupgrade Nov 3, 2026
6420a17
Tests: shared xd_as role helper and member-function query
jnasbyupgrade Nov 3, 2026
1eaa519
Tests: order the isnt_definer checks by name
jnasbyupgrade Nov 3, 2026
9866690
Tests: assert member functions with their SECURITY DEFINER flag; drop…
jnasbyupgrade Nov 3, 2026
5ae797e
Tests: tighten two comments
jnasbyupgrade Nov 3, 2026
007d795
Tests: use a block comment where the linter requires one
jnasbyupgrade Nov 3, 2026
165516f
Restore search_path after each registered SQL; consolidate drop_denie…
jnasbyupgrade Nov 4, 2026
36f69ec
Apply the search_path restore to the update script; drop vacuous stil…
jnasbyupgrade Nov 4, 2026
d3d6e18
Rename extension_drop__claim() to _extension_drop__dropping() and dro…
jnasbyupgrade Nov 4, 2026
f0b1d58
Put the terminator of multi-line statements on its own line
jnasbyupgrade Nov 4, 2026
8a90fe3
README: document pg_dump restore known issues
jnasbyupgrade Nov 4, 2026
ea11739
Put the sanity_assert statement terminator on its own line; fix two d…
jnasbyupgrade Nov 4, 2026
b85f62c
README: tell the reader to substitute public for xd in the duplicate-…
jnasbyupgrade Nov 4, 2026
5d440df
Trigger full CI matrix
jnasbyupgrade Nov 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ alone to have picked it up in that case.
never hardcodes a schema for any permanent object — the one
`CREATE SCHEMA __extension_drop` is transient scaffolding, created and
dropped within the same install script, not where anything permanent
lives. Its permanent functions pin their resolution via
`SET search_path FROM CURRENT` at creation time rather than
`@extschema@`-qualifying every reference; either technique gets to the
same schema-independence property. It's genuinely schema-flexible. See
`../ai/CLAUDE.md`'s "Schema-flexibility testing" section for the general
methodology (why `schema=` and not `relocatable=` is what matters, and how
to actually prove search_path-independence).
lives. Every permanent function sets `search_path = pg_catalog, pg_temp`
(so a role with CREATE on the extension's schema can't hijack operators or
functions) and refers to its own objects through `@extension_schema@`, which
the install and update scripts substitute with the quoted schema name.
Registered SQL runs under the event trigger's own pinned
`pg_catalog, pg_temp`, restored after each registration; the extension's
schema and dependency schemas (e.g. cat_tools) are not on that path, so
registered SQL must qualify everything. The extension itself is genuinely
schema-flexible. See `../ai/CLAUDE.md`'s "Schema-flexibility testing"
section for the general methodology (why `schema=` and not `relocatable=`
is what matters, and how to actually prove search_path-independence).

`test/install/load.sql` implements this by installing into a freshly
created, randomly named schema (a constant, quote-forcing prefix plus a
Expand All @@ -31,7 +35,10 @@ schema per test-file session (it never adds it to `search_path`, and
never assumes a naming convention beyond what it queries from
`pg_extension`/`pg_namespace` directly); `test/finish.sql` asserts at the
end of every test file that the schema was never reachable via
`search_path` regardless.
`search_path` regardless. It emits one assertion with the same label in
every mode; in existing mode (installed by an external pg_upgrade, placement
not ours to assert) that assertion is `pass()` and checks nothing, so a
single expected output serves all modes.

`https://github.com/Postgres-Extensions/pg_count_nulls/pull/55` is the
reference this was adapted from (not ported wholesale — see that PR, and
Expand Down
26 changes: 26 additions & 0 deletions HISTORY.asc
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
STABLE
------
== BREAKING: registered SQL now runs with `search_path = pg_catalog, pg_temp`
Existing registrations may break: SQL registered with `extension_drop__add()`
or `extension_drop__update()` can no longer rely on unqualified names. It
must schema-qualify everything it uses (for example cat_tools and
extension_drop's functions), or the `DROP` fails. Re-register (with
`extension_drop__update()`) any SQL that doesn't. See README.md.

== Drop support for PostgreSQL versions before 12
extension_drop depends on cat_tools, which already requires PostgreSQL
12+. A fresh install of extension_drop was already broken below that
too (a cat_tools function it calls needs PG11+ internally) -- this
just makes the declared floor honest.

== Require USAGE for PUBLIC on the extension's schema
`CREATE EXTENSION` and `ALTER EXTENSION ... UPDATE` now fail unless `PUBLIC`
has USAGE on the schema extension_drop is installed in, and new event
triggers protect that USAGE afterwards. See README.md for details.

== Run drop commands when `DROP SCHEMA ... CASCADE` or `DROP OWNED BY` drops an extension
The event trigger now fires for `DROP SCHEMA` and `DROP OWNED` as well as
`DROP EXTENSION`. Previously the other two commands left a stale registration
that made every later `DROP EXTENSION` fail with `XD001`; remove any with
`extension_drop__repair()`. Any role that can drop an extension can do so
without privileges on extension_drop's table; the registered SQL runs as that
role.
`extension_drop__sanity_assert()` now runs inside `_extension_drop__dropping()`,
before the registered SQL. See README.md.

== Fix `extension_drop__update()` and `extension_drop__remove()` with several registrations
With more than one extension registered, they changed every registration
instead of only the named one.

== Remove redundant client_min_messages handling from install script
`CREATE EXTENSION` already raises `client_min_messages` to `WARNING` for
the install script (only-raising, so a stricter caller is respected) and
Expand Down
161 changes: 153 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,51 @@
# extension_drop

Run custom commands when an extension is dropped. By default, `DROP
EXTENSION` simply drops all the objects the extension owns; this lets you
register additional SQL to run when a given extension is dropped.
Register SQL that runs when a given extension is dropped, whether by `DROP
EXTENSION`, `DROP SCHEMA ... CASCADE` or `DROP OWNED BY`. The registration is
removed with the extension.

Requires [cat_tools](https://pgxn.org/dist/cat_tools/) >= 0.3.0.

`PUBLIC` must have USAGE on the schema extension_drop is installed in. The
event trigger runs as whichever role drops an extension, and calls
`_extension_drop__dropping()` in that schema. The leading underscore marks
it as internal, not for external callers (the extension has no internal
schema); it is documented under [How it works](#how-it-works).

`CREATE EXTENSION` and `ALTER EXTENSION ... UPDATE` fail unless `PUBLIC` has
USAGE. The error's HINT gives the exact `GRANT USAGE ON SCHEMA ... TO PUBLIC`
to run first.

Two event triggers on `REVOKE` and `DROP OWNED` protect it afterwards:

- `extension_drop__usage_guard` (`ddl_command_end`) fails any command that
would remove USAGE, and the command has no effect.
- `extension_drop__usage_guard_start` (`ddl_command_start`) fails any such
command while `PUBLIC` already lacks USAGE. That happens if a superuser
bypassed the triggers, they were disabled or dropped, or the ACL arrived
through a restore.

Only the `extension_drop__usage_guard_start` error has the `GRANT` HINT for
recovering; run it.

Granting USAGE to `PUBLIC` also exposes every other object in that schema
that has `PUBLIC` privileges (functions are executable by `PUBLIC` by
default), so be careful about what schema you install it to.

## Functions

None of these are granted to `PUBLIC` except where noted, since
`extension_drop__add`/`extension_drop__update` let the caller register
arbitrary SQL to run later. Grant them to specific roles as needed.

- `extension_drop__add(extension_name name, sql text) RETURNS void`
Register `sql` to run when `extension_name` is dropped.
Register `sql` to run when `extension_name` is dropped. `sql` runs with
`search_path = pg_catalog, pg_temp`: schema-qualify everything it uses (see
[How it works](#how-it-works)).

- `extension_drop__update(extension_name name, sql text) RETURNS void`
Replace the SQL registered for `extension_name`.
Replace the SQL registered for `extension_name`. The same `search_path`
rule applies.

- `extension_drop__remove(extension_name name) RETURNS void`
Remove the SQL registered for `extension_name`.
Expand All @@ -34,6 +63,8 @@ arbitrary SQL to run later. Grant them to specific roles as needed.
- `extension_drop__sanity_assert(ignore name DEFAULT NULL) RETURNS void`
Raises an error if `extension_drop__sanity_check()` (called with the same
`ignore` argument) isn't empty. Granted to `PUBLIC` by default.
`_extension_drop__dropping` calls it, as its owner, so it runs with the
owner's rights.

- `extension_drop__repair() RETURNS void`
Deletes any stale rows found by `extension_drop__sanity_check()`. This
Expand All @@ -42,6 +73,120 @@ arbitrary SQL to run later. Grant them to specific roles as needed.
## How it works

An event trigger (`extension_drop`, on `sql_drop`) fires whenever an
extension is dropped, runs any SQL registered for it via
`extension_drop__add`/`extension_drop__update`, and removes the registration
afterward.
extension is dropped -- by `DROP EXTENSION`, `DROP SCHEMA ... CASCADE` or
`DROP OWNED BY` -- removes its registration from `extension_drop__commands`
and runs the SQL registered for it via
`extension_drop__add`/`extension_drop__update`. Those commands fire the
trigger for every drop, but it returns immediately unless an extension is
among the dropped objects.

Every extension_drop function pins `search_path = pg_catalog, pg_temp`, and
so does the registered SQL: it runs, as the dropping role, under the event
trigger's own pinned path. **Registered SQL must schema-qualify everything it
uses**: tables and functions in any schema (including cat_tools and
extension_drop's own functions). extension_drop's schema is whatever it was
installed into, so when registering, look it up and interpolate it with `%s`
(not `%I`: `regnamespace` output is already quoted):

SELECT extension_drop__add('my_extension',
format('SELECT %s.extension_drop__get(%L)',
extnamespace::regnamespace, 'my_extension'))
FROM pg_extension WHERE extname = 'extension_drop';

Nothing but `pg_catalog` and `pg_temp` is on the registered SQL's path, so a
role with CREATE on any schema can't plant objects that it resolves.
Registered SQL runs in no particular order when one command drops several
extensions.

Dropping an extension, registered or not, needs no privileges on
`extension_drop__commands`; the trigger gets the registered SQL from
`_extension_drop__dropping()`, which deletes the registration with its owner's
rights. The SQL itself runs as the dropping role, which may need further
privileges. A stale registration still fails the drop with `XD001`.

`_extension_drop__dropping() RETURNS TABLE(extension_name name, sql text)` is
internal; only the event trigger can use it. It deletes the registrations of
the extensions being dropped and returns them, in no particular order, and
errors when called outside a `sql_drop` trigger, so a direct call can't remove
the registration of a live extension. It is `SECURITY DEFINER` (with
`search_path = pg_catalog, pg_temp` and schema-qualified references), runs
`extension_drop__sanity_assert()` as its owner after the delete, and never
executes the SQL. Granted to `PUBLIC`. Its owner is the role that ran
`CREATE EXTENSION` (or the `ALTER EXTENSION ... UPDATE` that first created
it).

## Known issues

Restoring a `pg_dump` of a database that uses extension_drop has two
problems, tracked in
[#56](https://github.com/Postgres-Extensions/extension_tools/issues/56). The
commands below name the schema `xd` and the target database `newdb`; change
them to match (`xd` also appears inside the `grep` and `sed` patterns).
Schema names that need quoting are untested: `pg_restore -l` prints them
unquoted, but the `sed` pattern and the `GRANT` need them quoted.

### Restore into a schema other than `public` fails

**Create the schema and grant `USAGE` to `PUBLIC` before restoring the
rest.** Otherwise `CREATE EXTENSION` fails with `cannot install
extension_drop in schema "xd"`: pg_dump writes the `GRANT` only after all
extensions are created, and `pg_dump -x` never writes it. Installs into
`public` are not affected. Pre-creating the schema and then restoring the whole
dump only works without `-1`, and logs `schema "xd" already exists`.

Use this for `pg_restore`; it leaves out the commands data, so re-register
what is missing afterwards, as
[the next issue](#restore-fails-with-a-duplicate-key-on-extension_drop__commands)
describes:

pg_restore -l db.dump > all.list
grep -E '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - xd ' all.list > schema.list
grep -v -E '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - xd |TABLE DATA xd extension_drop__commands ' \
all.list > rest.list
pg_restore -1 -L schema.list -d newdb db.dump
psql -d newdb -c 'GRANT USAGE ON SCHEMA xd TO PUBLIC'
pg_restore -1 -L rest.list -d newdb db.dump

The last command also works with `-j 2` in place of `-1`, or with neither.

Use this for a plain SQL dump made without `--inserts`; it also leaves out
the commands data, so re-register afterwards:

psql -d newdb -c 'CREATE SCHEMA xd; GRANT USAGE ON SCHEMA xd TO PUBLIC'
sed '/^CREATE SCHEMA xd;$/d' db.sql \
| awk '/^COPY .*extension_drop__commands/{s=1}
!s{print}
s&&/^\\\.$/{s=0}' \
| psql -1 -v ON_ERROR_STOP=1 -d newdb

### Restore fails with a duplicate key on `extension_drop__commands`

For a schema other than `public`, use the recipes under
[Restore into a schema other than `public` fails](#restore-into-a-schema-other-than-public-fails),
which already leave this data out. The recipes below apply when extension_drop
is in `public`; replace `xd` with `public` in them.

**Leave the data of `extension_drop__commands` out of the restore, then
re-register what your extensions' install scripts don't register.** When an
extension registers drop SQL in its install script, `CREATE EXTENSION`
re-registers it during the restore and the dump's `COPY` then inserts the same
row, failing with `duplicate key value violates unique constraint
"extension_drop__commands_pkey"`. The failed `COPY` inserts none of its rows,
so a restore that continues past it (`psql -f`, `pg_restore` without `-1`, with
or without `-j`) also loses registrations made by direct
`extension_drop__add()` calls. A `-1` restore, or `psql -1`, aborts and
restores nothing.

List the registrations in the source database before dumping, to know which
ones to re-register:

SELECT * FROM xd.extension_drop__commands;

Leave the data out when dumping (the pattern must be schema-qualified; an
unqualified name silently excludes nothing):

pg_dump -Fc --exclude-table-data='xd.extension_drop__commands' -f db.dump db

Then, for each registration the restored database lacks:

SELECT xd.extension_drop__add('my_extension', 'SELECT 1');
Loading
Loading