35.15. Packaging Related Objects into an Extension
A useful extension toPostgres Pro typically includes multiple SQL objects; for example, a new data type will require new functions, new operators, and probably new index operator classes. It is helpful to collect all these objects into a single package to simplify database management.Postgres Pro calls such a package anextension. To define an extension, you need at least ascript file that contains theSQL commands to create the extension's objects, and acontrol file that specifies a few basic properties of the extension itself. If the extension includes C code, there will typically also be a shared library file into which the C code has been built. Once you have these files, a simpleCREATE EXTENSION command loads the objects into your database.
The main advantage of using an extension, rather than just running theSQL script to load a bunch of“loose” objects into your database, is thatPostgres Pro will then understand that the objects of the extension go together. You can drop all the objects with a singleDROP EXTENSION command (no need to maintain a separate“uninstall” script). Even more useful,pg_dump knows that it should not dump the individual member objects of the extension — it will just include aCREATE EXTENSION
command in dumps, instead. This vastly simplifies migration to a new version of the extension that might contain more or different objects than the old version. Note however that you must have the extension's control, script, and other files available when loading such a dump into a new database.
Postgres Pro will not let you drop an individual object contained in an extension, except by dropping the whole extension. Also, while you can change the definition of an extension member object (for example, viaCREATE OR REPLACE FUNCTION
for a function), bear in mind that the modified definition will not be dumped bypg_dump. Such a change is usually only sensible if you concurrently make the same change in the extension's script file. (But there are special provisions for tables containing configuration data; see below.)
The extension mechanism also has provisions for packaging modification scripts that adjust the definitions of the SQL objects contained in an extension. For example, if version 1.1 of an extension adds one function and changes the body of another function compared to 1.0, the extension author can provide anupdate script that makes just those two changes. TheALTER EXTENSION UPDATE
command can then be used to apply these changes and track which version of the extension is actually installed in a given database.
The kinds of SQL objects that can be members of an extension are shown in the description ofALTER EXTENSION. Notably, objects that are database-cluster-wide, such as databases, roles, and tablespaces, cannot be extension members since an extension is only known within one database. (Although an extension script is not prohibited from creating such objects, if it does so they will not be tracked as part of the extension.) Also notice that while a table can be a member of an extension, its subsidiary objects such as indexes are not directly considered members of the extension. Another important point is that schemas can belong to extensions, but not vice versa: an extension as such has an unqualified name and does not exist“within” any schema. The extension's member objects, however, will belong to schemas whenever appropriate for their object types. It may or may not be appropriate for an extension to own the schema(s) its member objects are within.
35.15.1. Defining Extension Objects
Widely-distributed extensions should assume little about the database they occupy. In particular, unless you issuedSET search_path = pg_temp
, assume each unqualified name could resolve to an object that a malicious user has defined. Beware of constructs that depend onsearch_path
implicitly:IN
andCASE
always select an operator using the search path. In their place, useexpression
WHENOPERATOR(
andschema
.=) ANYCASE WHEN
.expression
35.15.2. Extension Files
TheCREATE EXTENSION command relies on a control file for each extension, which must be named the same as the extension with a suffix of The file format for an extension control file is the same as for the A control file can set the following parameters: The directory containing the extension'sSQL script file(s). Unless an absolute path is given, the name is relative to the installation's The default version of the extension (the one that will be installed if no version is specified in A comment (any string) about the extension. Alternatively, the comment can be set by means of theCOMMENT command in the script file. The character set encoding used by the script file(s). This should be specified if the script files contain any non-ASCII characters. Otherwise the files will be assumed to be in the database encoding. The value of this parameter will be substituted for each occurrence of A list of names of extensions that this extension depends on, for example If this parameter is An extension isrelocatable if it is possible to move its contained objects into a different schema after initial creation of the extension. The default is This parameter can only be set for non-relocatable extensions. It forces the extension to be loaded into exactly the named schema and not any other. See below for more information. In addition to the primary control file.control
, and must be placed in the installation'sSHAREDIR/extension
directory. There must also be at least oneSQL script file, which follows the naming pattern
(for example,extension
--version
.sqlfoo--1.0.sql
for version1.0
of extensionfoo
). By default, the script file(s) are also placed in theSHAREDIR/extension
directory; but the control file can specify a different directory for the script file(s).postgresql.conf
file, namely a list ofparameter_name
=
value
assignments, one per line. Blank lines and comments introduced by#
are allowed. Be sure to quote any value that is not a single word or number.directory
(string
)SHAREDIR
directory. The default behavior is equivalent to specifyingdirectory = 'extension'
.default_version
(string
)CREATE EXTENSION
). Although this can be omitted, that will result inCREATE EXTENSION
failing if noVERSION
option appears, so you generally don't want to do that.comment
(string
)encoding
(string
)module_pathname
(string
)MODULE_PATHNAME
in the script file(s). If it is not set, no substitution is made. Typically, this is set to$libdir/
and thenshared_library_name
MODULE_PATHNAME
is used inCREATE FUNCTION
commands for C-language functions, so that the script files do not need to hard-wire the name of the shared library.requires
(string
)requires = 'foo, bar'
. Those extensions must be installed before this one can be installed.superuser
(boolean
)true
(which is the default), only superusers can create the extension or update it to a new version. If it is set tofalse
, just the privileges required to execute the commands in the installation or update script are required.relocatable
(boolean
)false
, i.e. the extension is not relocatable. See below for more information.schema
(string
)
, an extension can have secondary control files named in the styleextension
.control
. If supplied, these must be located in the script file directory. Secondary control files follow the same format as the primary control file. Any parameters set in a secondary control file override the primary control file when installing or updating to that version of the extension. However, the parametersextension
--version
.controldirectory
anddefault_version
cannot be set in a secondary control file.
35.15.3. Extension Relocatability
Users often wish to load the objects contained in an extension into a different schema than the extension's author had in mind. There are three supported levels of relocatability:
A fully relocatable extension can be moved into another schema at any time, even after it's been loaded into a database. This is done with the
ALTER EXTENSION SET SCHEMA
command, which automatically renames all the member objects into the new schema. Normally, this is only possible if the extension contains no internal assumptions about what schema any of its objects are in. Also, the extension's objects must all be in one schema to begin with (ignoring objects that do not belong to any schema, such as procedural languages). Mark a fully relocatable extension by settingrelocatable = true
in its control file.An extension might be relocatable during installation but not afterwards. This is typically the case if the extension's script file needs to reference the target schema explicitly, for example in setting
search_path
properties for SQL functions. For such an extension, setrelocatable = false
in its control file, and use@extschema@
to refer to the target schema in the script file. All occurrences of this string will be replaced by the actual target schema's name before the script is executed. The user can set the target schema using theSCHEMA
option ofCREATE EXTENSION
.If the extension does not support relocation at all, set
relocatable = false
in its control file, and also setschema
to the name of the intended target schema. This will prevent use of theSCHEMA
option ofCREATE EXTENSION
, unless it specifies the same schema named in the control file. This choice is typically necessary if the extension contains internal assumptions about schema names that can't be replaced by uses of@extschema@
. The@extschema@
substitution mechanism is available in this case too, although it is of limited use since the schema name is determined by the control file.
In all cases, the script file will be executed withsearch_path initially set to point to the target schema; that is,CREATE EXTENSION
does the equivalent of this:
SET LOCAL search_path TO @extschema@;
This allows the objects created by the script file to go into the target schema. The script file can changesearch_path
if it wishes, but that is generally undesirable.search_path
is restored to its previous setting upon completion ofCREATE EXTENSION
.
The target schema is determined by theschema
parameter in the control file if that is given, otherwise by theSCHEMA
option ofCREATE EXTENSION
if that is given, otherwise the current default object creation schema (the first one in the caller'ssearch_path
). When the control fileschema
parameter is used, the target schema will be created if it doesn't already exist, but in the other two cases it must already exist.
If any prerequisite extensions are listed inrequires
in the control file, their target schemas are appended to the initial setting ofsearch_path
. This allows their objects to be visible to the new extension's script file.
Although a non-relocatable extension can contain objects spread across multiple schemas, it is usually desirable to place all the objects meant for external use into a single schema, which is considered the extension's target schema. Such an arrangement works conveniently with the default setting ofsearch_path
during creation of dependent extensions.
35.15.4. Extension Configuration Tables
Some extensions include configuration tables, which contain data that might be added or changed by the user after installation of the extension. Ordinarily, if a table is part of an extension, neither the table's definition nor its content will be dumped bypg_dump. But that behavior is undesirable for a configuration table; any data changes made by the user need to be included in dumps, or the extension will behave differently after a dump and reload.
To solve this problem, an extension's script file can mark a table it has created as a configuration table, which will causepg_dump to include the table's contents (not its definition) in dumps. To do that, call the functionpg_extension_config_dump(regclass, text)
after creating the table, for example
CREATE TABLE my_config (key text, value text);SELECT pg_catalog.pg_extension_config_dump('my_config', '');
Any number of tables can be marked this way.
When the second argument ofpg_extension_config_dump
is an empty string, the entire contents of the table are dumped bypg_dump. This is usually only correct if the table is initially empty as created by the extension script. If there is a mixture of initial data and user-provided data in the table, the second argument ofpg_extension_config_dump
provides aWHERE
condition that selects the data to be dumped. For example, you might do
CREATE TABLE my_config (key text, value text, standard_entry boolean);SELECT pg_catalog.pg_extension_config_dump('my_config', 'WHERE NOT standard_entry');
and then make sure thatstandard_entry
is true only in the rows created by the extension's script.
More complicated situations, such as initially-provided rows that might be modified by users, can be handled by creating triggers on the configuration table to ensure that modified rows are marked correctly.
You can alter the filter condition associated with a configuration table by callingpg_extension_config_dump
again. (This would typically be useful in an extension update script.) The only way to mark a table as no longer a configuration table is to dissociate it from the extension withALTER EXTENSION ... DROP TABLE
.
Note that foreign key relationships between these tables will dictate the order in which the tables are dumped out by pg_dump. Specifically, pg_dump will attempt to dump the referenced-by table before the referencing table. As the foreign key relationships are set up at CREATE EXTENSION time (prior to data being loaded into the tables) circular dependencies are not supported. When circular dependencies exist, the data will still be dumped out but the dump will not be able to be restored directly and user intervention will be required.
35.15.5. Extension Updates
One advantage of the extension mechanism is that it provides convenient ways to manage updates to the SQL commands that define an extension's objects. This is done by associating a version name or number with each released version of the extension's installation script. In addition, if you want users to be able to update their databases dynamically from one version to the next, you should provideupdate scripts that make the necessary changes to go from one version to the next. Update scripts have names following the pattern
(for example,extension
--old_version
--target_version
.sqlfoo--1.0--1.1.sql
contains the commands to modify version1.0
of extensionfoo
into version1.1
).
Given that a suitable update script is available, the commandALTER EXTENSION UPDATE
will update an installed extension to the specified new version. The update script is run in the same environment thatCREATE EXTENSION
provides for installation scripts: in particular,search_path
is set up in the same way, and any new objects created by the script are automatically added to the extension.
If an extension has secondary control files, the control parameters that are used for an update script are those associated with the script's target (new) version.
The update mechanism can be used to solve an important special case: converting a“loose” collection of objects into an extension. Before the extension mechanism was added toPostgreSQL (in 9.1), many people wrote extension modules that simply created assorted unpackaged objects. Given an existing database containing such objects, how can we convert the objects into a properly packaged extension? Dropping them and then doing a plainCREATE EXTENSION
is one way, but it's not desirable if the objects have dependencies (for example, if there are table columns of a data type created by the extension). The way to fix this situation is to create an empty extension, then useALTER EXTENSION ADD
to attach each pre-existing object to the extension, then finally create any new objects that are in the current extension version but were not in the unpackaged release.CREATE EXTENSION
supports this case with itsFROM
old_version
option, which causes it to not run the normal installation script for the target version, but instead the update script named
. The choice of the dummy version name to use asextension
--old_version
--target_version
.sqlold_version
is up to the extension author, thoughunpackaged
is a common convention. If you have multiple prior versions you need to be able to update into extension style, use multiple dummy version names to identify them.
ALTER EXTENSION
is able to execute sequences of update script files to achieve a requested update. For example, if onlyfoo--1.0--1.1.sql
andfoo--1.1--2.0.sql
are available,ALTER EXTENSION
will apply them in sequence if an update to version2.0
is requested when1.0
is currently installed.
Postgres Pro doesn't assume anything about the properties of version names: for example, it does not know whether1.1
follows1.0
. It just matches up the available version names and follows the path that requires applying the fewest update scripts. (A version name can actually be any string that doesn't contain--
or leading or trailing-
.)
Sometimes it is useful to provide“downgrade” scripts, for examplefoo--1.1--1.0.sql
to allow reverting the changes associated with version1.1
. If you do that, be careful of the possibility that a downgrade script might unexpectedly get applied because it yields a shorter path. The risky case is where there is a“fast path” update script that jumps ahead several versions as well as a downgrade script to the fast path's start point. It might take fewer steps to apply the downgrade and then the fast path than to move ahead one version at a time. If the downgrade script drops any irreplaceable objects, this will yield undesirable results.
To check for unexpected update paths, use this command:
SELECT * FROM pg_extension_update_paths('extension_name
');
This shows each pair of distinct known version names for the specified extension, together with the update path sequence that would be taken to get from the source version to the target version, orNULL
if there is no available update path. The path is shown in textual form with--
separators. You can useregexp_split_to_array(path,'--')
if you prefer an array format.
35.15.6. Extension Example
Here is a complete example of anSQL-only extension, a two-element composite type that can store any type of value in its slots, which are named“k” and“v”. Non-text values are automatically coerced to text for storage. The script file The control file While you hardly need a makefile to install these two files into the correct directory, you could use a This makefile relies onPGXS, which is described inSection 35.16. The command Once the files are installed, use theCREATE EXTENSION command to load the objects into any particular database.pair--1.0.sql
looks like this:-- complain if script is sourced in psql, rather than via CREATE EXTENSION\echo Use "CREATE EXTENSION pair" to load this file. \quitCREATE TYPE pair AS ( k text, v text );CREATE OR REPLACE FUNCTION pair(text, text)RETURNS pair LANGUAGE SQL AS 'SELECT ROW($1, $2)::@extschema@.pair;';CREATE OPERATOR ~> (LEFTARG = text, RIGHTARG = text, PROCEDURE = pair);-- "SET search_path" is easy to get right, but qualified names perform better.CREATE OR REPLACE FUNCTION lower(pair)RETURNS pair LANGUAGE SQLAS 'SELECT ROW(lower($1.k), lower($1.v))::@extschema@.pair;'SET search_path = pg_temp;CREATE OR REPLACE FUNCTION pair_concat(pair, pair)RETURNS pair LANGUAGE SQLAS 'SELECT ROW($1.k OPERATOR(pg_catalog.||) $2.k, $1.v OPERATOR(pg_catalog.||) $2.v)::@extschema@.pair;';
pair.control
looks like this:# pair extensioncomment = 'A key/value pair data type'default_version = '1.0'relocatable = false
Makefile
containing this:EXTENSION = pairDATA = pair--1.0.sqlPG_CONFIG = pg_configPGXS := $(shell $(PG_CONFIG) --pgxs)include $(PGXS)
make install
will install the control and script files into the correct directory as reported bypg_config.