1. Finding out if and which extension is being installed
All one has to do to find out if an extension is currently being installed is to create any type of object that would normally become tracked as part of the extension (i.e., any object type that can be appropriated or disowned via
ALTER EXTENSION.), and then check (via the
pg_depend catalog) if that object now depends on an extension (and which extension that is).
The object being tested for belonging to an extension may even be a temporary object:
create temporary table test_object (col int)
on commit drop;
on pg_extension.oid = pg_depend.refobjid
pg_depend.classid = 'pg_catalog.pg_class'::regclass
and pg_depend.objid = 'test_object'::regclass
and pg_depend.refclassid = 'pg_catalog.pg_extension'::regclass
SELECT will return
NULL if this code is run outside of a
ALTER EXTENSION context. Otherwise, it will return the name of the extension that is in the process of being installed. (If an extension is being installed due to a dependent extension being installed
WITH CASCADE, the extension name returned will be the name of the dependency, not the dependent.)
Of course, normally there would scarcely be a reason to create a dummy object, since the point of many extension set up and upgrade scripts is to create objects anyway.
2. Finding out if the current event trigger fires in the context of an extension script
I could have just turned to the event trigger documentation for the answer: https://www.postgresql.org/docs/current/functions-event-triggers.html
One of the columns in the
record set that
pg_event_trigger_ddl_commands() returns is:
in_extension, which is “[t]rue if the command is part of an extension script”.