Relational databases
Types and extensions in PostgreSQL
A PostgreSQL type gives a value its meaning, and an operator asks a question about that value. A reservation can be one time range, with an operator for overlap. A location can be a spatial value, with a predicate for distance. An appropriate index can then help answer that same question without examining every row.
Some of that support is built in. Extensions add related objects such as types, functions, operators and index operator classes. Once an application stores their values or relies on their rules, those objects become part of what it must recover. Keeping the rows is insufficient if the replacement server cannot read them or enforce the same constraint.
Follow room R1’s reservation 7001, from its time boundaries to the extension supporting its non-overlap rule. A separate mathematical example develops spatial distance. Then follow the reservation’s dependencies through installation, restore, updating and removal. PostgreSQL index methods and operators explains the index structures; here the question is which meaning and software the application depends on.
Ranges, bounds and overlap
A range represents the values between two bounds. tstzrange is PostgreSQL’s built-in range of timestamp-with-time-zone values: instants, rather than unqualified wall-clock readings. Reservation 7001 occupies R1 on 2 November 2026 from 10:00 up to 11:00 UTC:
SELECT tstzrange(
'2026-11-02 10:00+00', '2026-11-02 11:00+00', '[)');The [) argument includes the start and excludes the end. At exactly 11:00, this reservation has finished. That lets the next reservation begin at 11:00 without sharing an instant. The type also permits other bounds and empty ranges, so choosing tstzrange does not by itself enforce this booking policy.
Attempt 7002 starts at 10:30 and ends at 11:30. Attempt 7003 starts at 11:00 and ends at 12:00. Consider each attempt independently against 7001. The 10:30 start shares time with it; the 11:00 start touches only its excluded end, leaving no shared instant.
Figure as text
The existing room reservation includes 10:00 and excludes 11:00. The 10:30 attempt overlaps and is refused. The 11:00 attempt starts exactly at the excluded end, adjoins without overlap, and is permitted.
&& asks whether two ranges overlap: whether they have any value in common. @> asks whether a range contains a value or another range. -|- asks whether two ranges are adjacent. Adjacency and overlap are different predicates. The boundary policy explains why 7003 adjoins 7001 while && returns false.
SELECT reservation_id
FROM reservations
WHERE room = 'R1'
AND during && tstzrange(
'2026-11-02 10:30+00', '2026-11-02 11:30+00', '[)');
-- 7001This is a search. It does not prevent another caller from inserting an overlap after the search. To enforce non-overlap, the reservation table needs an exclusion constraint: no pair of rows may have both equal rooms and overlapping times. Constraints and data integrity develops that integrity argument, including why checking in application code is insufficient.
Combining room equality with time overlap
The constraint uses GiST support for both comparisons. PostgreSQL already supplies the range operator class. A text room identifier needs a GiST class for text equality; the supplied btree_gist extension adds it. Despite its name, this is GiST support with B-tree-like comparisons, rather than a B-tree index alongside the range index.
-- After deliberately installing btree_gist, as below:
CREATE TABLE reservations (
reservation_id integer PRIMARY KEY,
room text NOT NULL,
during tstzrange NOT NULL,
CHECK (
NOT isempty(during)
AND NOT lower_inf(during) AND NOT upper_inf(during)
AND lower_inc(during) AND NOT upper_inc(during)
AND isfinite(lower(during)) AND isfinite(upper(during))
),
CONSTRAINT room_free
EXCLUDE USING gist (room WITH =, during WITH &&)
);The check requires a non-empty range with finite, present bounds and the chosen half-open policy. The exclusion rejects the pair only when both comparisons are true; another room can use the same interval. Adding a plain GiST search index would supply an access path without supplying this rule. Nor does btree_gist make GiST a general replacement for B-tree uniqueness.
In the native reservation check, creating this kind of exclusion without the extension failed because text had no default GiST operator class. With btree_gist installed, 7002 was refused with an exclusion violation and 7003 was permitted. The range type and its overlap meaning were present before the extension; the missing part was the text index support needed to combine them.
Spatial types and predicates
PostgreSQL’s built-in point, box, polygon and related geometric types represent two-dimensional Cartesian objects. They suit questions on a plane whose coordinate meaning the application already controls. For example, point(3,4) <-> point(0,0) gives distance 5. Nothing in that value declares metres, longitude or a map projection.
PostGIS adds geometry, geography and spatial operations. A geometry’s spatial reference identifier, or SRID, identifies its coordinate reference system. Planar geometry distances use that system’s units. A WGS 84 longitude/latitude geometry has angular coordinates, so asking for distance 500 does not ask for 500 metres. A suitable projected coordinate system can provide metre-based planar calculations, within its intended area and accuracy.
Geography instead supports Earth-distance calculations with distances in metres; ST_DWithin uses a spheroid by default. That choice affects meaning and cost. Choose from the extent and accuracy of the actual question, rather than casting until a query accepts the operands.
Assigning an SRID is also different from transforming coordinates. ST_SetSRID labels the existing numbers. ST_Transform calculates coordinates in another reference system. Labelling longitude/latitude numbers as a projected metre system does not convert them into metres.
Finding points within a distance
Consider points at most 5 coordinate units from the origin. Any match must lie inside the square from −5 to 5 on each axis, so that box can cheaply exclude point C at (6,0). Point A at (3,4) and point B at (4,4) both remain candidates. Their distances are 5 and √32, about 5.66: only A satisfies the actual radius.
Figure as text
The square from −5 to 5 excludes C at (6,0). A at (3,4) and B at (4,4) remain candidates. The distance test keeps A at exactly 5 and rejects B at square root 32, about 5.66.
The box is a candidate filter, not the definition of the answer. PostGIS’s ST_DWithin includes an index-aware bounding-box comparison and the distance test; the application keeps the complete predicate in its SQL.
-- In a PostGIS-enabled database; locations are a separate application table.
CREATE TABLE locations (
location_id integer PRIMARY KEY,
position geography(Point, 4326) NOT NULL
);
CREATE INDEX locations_position_gist
ON locations USING gist (position);
-- $1 = longitude, $2 = latitude; distance is in metres.
SELECT location_id
FROM locations
WHERE ST_DWithin(
position,
ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography,
500
);This query stores geography, builds its GiST support and queries that same column as geography. Its coordinates must actually be WGS 84 longitude then latitude. The preceding coordinate arithmetic explains candidate filtering in a plane; it is not an Earth-distance calculation or an observed execution of this query.
Changing the query to a transformed or cast expression changes what an index must support. An index on a geometry column does not automatically supply an index on every transformation or geography cast of it. Match the stored type, operator, expression and class, then inspect the actual plan on representative data. An eligible index can still lose to a scan, especially for a broad radius or a tiny table. The PostGIS example is documentation-based here; no PostGIS execution or speed measurement is claimed.
Installing an extension
There are two installations to keep separate. The server needs the extension’s supporting files: its control file, SQL scripts and, for compiled functions, the appropriate library and supporting libraries. A package, server image or managed-service capability supplies those files. CREATE EXTENSION then runs an installation script in one database and records the resulting objects as members of that extension.
Provisioning files does not install the extension in every database. Conversely, an application’s CREATE EXTENSION cannot download a missing server library. Inspect both available software and the current database before choosing a version:
SELECT name, default_version, installed_version
FROM pg_available_extensions
WHERE name IN ('btree_gist', 'postgis');
SELECT version, installed, superuser, trusted,
relocatable, schema, requires
FROM pg_available_extension_versions
WHERE name = 'btree_gist'
ORDER BY version;
SELECT extname, extversion, extowner::regrole,
extnamespace::regnamespace
FROM pg_extension;default_version is the server files’ default choice; extversion is what this database has installed. The version rows also expose prerequisites, trusted-installation eligibility and schema restrictions. A supplied extension can require other extensions first. Inspect those versions and schemas too; a convenient CASCADE installation can choose prerequisite defaults you did not explicitly select.
The extension name is database-wide, even when its exported objects live in a schema. SCHEMA chooses an allowed destination for those objects; it cannot override a fixed schema required by the extension. Relocatability is another property to inspect before planning to move them.
Installation authority and application access
Use the collection’s separate shop_migrate and shop_runtime authorities. Provisioning server software belongs to the server operator or service administrator. Installing its database objects belongs to a deliberate migration or extension administrator. Runtime needs only the operations that use them.
btree_gist is trusted: a non-superuser with CREATE on the database can install it. Trusted is permission to use that installation path, rather than a claim that every extension is safe for every application. Many other extensions need superuser authority. Check the chosen version’s requirements and the service’s supported procedure.
-- Administrator prepares the authority and protected destination:
GRANT CREATE ON DATABASE shop_database TO shop_migrate;
CREATE SCHEMA extensions AUTHORIZATION shop_migrate;
-- Separate deployment connection assumes shop_migrate.
-- Substitute the version approved from the inspection above.
CREATE EXTENSION btree_gist
WITH SCHEMA extensions VERSION '1.8';
-- Runtime may resolve granted objects, but cannot create in this schema:
GRANT USAGE ON SCHEMA extensions TO shop_runtime;Version 1.8 is the choice observed in the PostgreSQL 18.6 fixture, not a universal version to paste into a migration. Keep database CREATE, schema creation rights and ownership away from runtime. For trusted installation, the caller owns the extension while its member objects are normally owned by the bootstrap superuser. Owning the extension does not mean owning each function or operator class.
Protect the installation schema and prerequisite schemas from untrusted object creation. Installation scripts resolve names, so a hostile object on their search path can change what privileged code calls. Ordinary callers also need suitable schema USAGE and any required function or type privileges; inspect the extension’s actual grants rather than assuming installation granted the intended access. PostgreSQL roles, policies and privileged code develops membership, ownership and safe name resolution.
For the reservation DDL, include the protected extensions schema in the migration’s deliberate search path so the text operator class can be resolved. Keep untrusted schemas out of privileged paths. CREATE EXTENSION IF NOT EXISTS is not a compatibility test: an existing extension with that name can have another version or history.
Extension objects and application dependencies
The reservation table is an application object. It does not become a member of btree_gist merely by using it. Its exclusion constraint has a supporting GiST index; the text key uses the extension’s operator class. Preserving the rule therefore requires both the installed operator class and the compatible server files that implement it.
- Application · reservations↓ exclusion constraint · same room and overlapping time
- room_free · supporting GiST index↓ index uses text equality class + built-in range class
- gist_text_ops · extension member↓ membership recorded in PostgreSQL
- btree_gist · installed extension↓ implementation supplied outside the database catalogue
- Server control file · SQL scripts · compiled library
A dependency map, not an execution path. Solid boxes describe database objects and recorded relationships; the dashed box is server software which a database dump does not contain. The application table and rule remain separately owned objects.
There are three relationships to distinguish. Membership groups an extension’s own objects. A declared prerequisite makes one extension require another. An application dependency connects an object such as this index to a type or class the extension provides. pg_depend records these catalogue relationships; pg_describe_object turns its object addresses into readable descriptions.
SELECT pg_describe_object(d.classid, d.objid, d.objsubid)
AS member
FROM pg_depend AS d
JOIN pg_extension AS e ON e.oid = d.refobjid
WHERE d.refclassid = 'pg_extension'::regclass
AND d.deptype = 'e'
AND e.extname = 'btree_gist';This lists members, not the complete application inventory. Catalogue tracking cannot discover a client query stored outside the database. It also need not record references hidden inside dynamic SQL or a routine body supplied as a string. Inventory callers, migrations, generated expressions, stored values and operational tools as well as catalogue dependants. An extension used only by a report still has a caller even when dropping it meets no catalogue objection.
Restoring extension data and behaviour
A logical dump normally requests extension creation instead of dumping each member’s definition. The installation script reconstructs those objects. The dump carries the application table, its rows, its constraint and its grants, but the destination must already have compatible extension files.
A destination lacking those files cannot recreate the extension merely by receiving the dump. Restore preparation must supply the software as well as the saved database definitions and rows.
Figure as text
The logical dump requests extension creation and carries application definitions, data and grants. Compatible control files, scripts and libraries must already be provisioned on the target server. Without them, copying the dump cannot complete extension creation.
A dump’s extension creation need not pin the source’s exact version. Inspect the emitted command and prepare the intended target version under the extension’s documented restore procedure. A changed default can reconstruct different objects. The extension name and a successful row load therefore establish less than a recovered application. In this dump the command selected the target default, with no VERSION clause.
The reservation rehearsal restored a logical dump into a separate PostgreSQL 18.6 cluster. Under the runtime role’s grants, 7001 remained readable and its range contained 10:30. An overlapping 7002 was refused and an adjoining 7003 was permitted. The check used the same provisioned extension files at both ends, so it shows only that this reconstruction works. It does not show cross-version compatibility or recovery on an unprepared host.
Ownership also needed checking. The restored extension belonged to the restoring administrator, while the application table returned to its migration owner. Do not assume the original extension’s owner followed the dump.
The extension in the recovery contract
Keep a reproducible way to supply compatible extension software for every recovery and standby target. That means the right PostgreSQL major version and platform, the extension’s libraries and scripts, any supporting libraries, the required configuration and any external data the extension uses. A file-level backup or archived WAL does not package all software outside the data directory. A standby which needs a library must have that library available too.
There are special data cases. An extension can register configuration-table contents for inclusion in a dump, possibly with a row filter; ordinary member definitions remain reconstructed by installation. Conversely, a hand-edited member function definition is generally omitted by pg_dump, so it can disappear on restore. Use the extension’s supported update mechanism for such changes and test configuration data explicitly.
The acceptance question is whether the recovered service preserves the relevant values and decisions. Check representative stored values, predicates, constraints, indexes and actual caller access. For a spatial extension, include reference-system handling and required transformation resources. For a search extension, include expected matches. Backup, restore and reconciliation develops the wider recovery chain and valid work outside the restored history.
Updating extension software and database objects
Replacing a server package changes available software. It does not by itself run the update scripts for every database using the extension. ALTER EXTENSION … UPDATE changes one database’s extension objects along an available script path. The extension’s release procedure must say which software and SQL steps belong together, including any restart, stored-data conversion or index rebuild.
SELECT extversion FROM pg_extension
WHERE extname = 'btree_gist';
SELECT source, target, path
FROM pg_extension_update_paths('btree_gist')
WHERE source = '1.2' AND target = '1.8';
-- Only after accepting this supported path on a recoverable copy:
ALTER EXTENSION btree_gist UPDATE TO '1.8';The path reports scripts available to this server, not a guarantee that the application accepts their effect. A path may traverse intermediate versions. Its source can also be an older installed version that these files cannot create afresh; check installation availability separately when preparing a test copy. Version labels are supplied by the extension; do not infer a usable transition by comparing their spelling. A successful ALTER EXTENSION also does not perform every external maintenance task an extension’s release requires.
Rehearse with the stored data and the real callers’ authority. Check that operator results still express the same business question, old values remain readable, constraints still refuse forbidden writes and indexes meet the release’s validity and rebuild requirements. Check allowed writes too: a rule that refuses everything is not a successful update. Preserve a tested recovery route before admitting new application work under the changed representation.
The native rehearsal updated btree_gist from 1.2 to 1.8 through the advertised intermediate scripts. The stored range still contained 10:30. The exclusion still rejected 7002, and adjoining 7003 was still permitted. The files advertised no reverse path from 1.8 to 1.2.
That small check is evidence about that path and rule. It is not an acceptance suite for PostGIS or another extension. A reverse script is not guaranteed, and replacing an old library over newly changed objects is not a downgrade procedure. Upgrading and migrating PostgreSQL handles the whole-server transfer and write handover.
Removing an extension
DROP EXTENSION removes its database objects. The default RESTRICT refuses when recorded outside dependencies still need them. In the reservation example, that refusal protects the exclusion rule’s reliance on the text class. It is a useful inventory signal, not proof that every application caller has been found.
CASCADE permits removal of dependants too. In the disposable reservation test it removed the exclusion constraint and its supporting index while leaving row 7001 in the table. A new overlapping 7002 could then be inserted. The rows survived, but the booking rule did not.
| Attempt | Observed result | Reservation service |
|---|---|---|
DROP EXTENSION btree_gist RESTRICT | Refused: outside dependency | Rule and stored row retained |
DROP EXTENSION btree_gist CASCADE | Extension, rule and index removed; row retained | Overlapping insert accepted |
Another extension can have a different loss boundary. If a table column uses an extension-defined type, a cascade can remove that column and its values. Establish the complete effect on a recoverable copy before choosing a drop. First remove caller reliance and migrate any values that need a replacement representation. Supply replacement enforcement before reopening writes that depended on the old rule.
Dropping an extension does not uninstall its server files and is not an update method. Keep those files while any database or retained recovery history still needs them. The decision reaches beyond the currently connected database: the software can serve other databases, standbys and restores of older backups.
What was checked
The displayed reservation definition, range predicates and built-in point calculations were checked in PGlite 0.5.8, PostgreSQL 18.3 in WebAssembly. Installation, catalogue dependencies, exclusion outcomes, logical restore and the available update path were checked separately. These checks ran on an owned disposable PostgreSQL 18.6 Linux server, with isolated source and restore clusters and explicit Unix sockets.
Role checks used administrator SET ROLE under local trust authentication; they establish effective grants here, rather than deployed login authentication. The adjoining attempts and destructive removal branch were rolled back. Each fixture retained only its starting reservation.
The drawings explain value semantics and dependencies. They are not page layouts, planner traces or concurrent schedules. The spatial SQL follows PostGIS’s documented interface; the square-and-circle arithmetic was checked, but no PostGIS runtime was available. No observation establishes production speed. Keep the same distinction in an application rehearsal: a completed command, a correct result and a recoverable service are separate things to demonstrate.