52.18. pg_depend

В каталоге pg_depend записываются отношения зависимости между объектами базы данных. Благодаря этой информации, команды DROP могут найти, какие объекты должны удаляться при использовании DROP CASCADE, или когда нужно запрещать удаление при DROP RESTRICT.

Также смотрите описание каталога pg_shdepend, который играет подобную роль в отношении совместно используемых объектов в кластере баз данных.

Таблица 52.18. Столбцы pg_depend

ИмяТипСсылкиОписание
classidoidpg_class.oidOID системного каталога, в котором находится зависимый объект
objidoidлюбой столбец OIDOID определённого зависимого объекта
objsubidint4 Для столбца таблицы это номер столбца (objid и classid указывают на саму таблицу). Для всех других типов объектов это поле содержит ноль.
refclassidoidpg_class.oidOID системного каталога, в котором находится вышестоящий объект
refobjidoidлюбой столбец OIDOID определённого вышестоящего объекта
refobjsubidint4 Для столбца таблицы это номер столбца (refobjid и refclassid указывают на саму таблицу). Для всех других типов объектов это поле содержит ноль.
deptypechar Код, определяющий конкретную семантику данного отношения зависимости; см. текст

Во всех случаях, запись в pg_depend показывает, что вышестоящий объект нельзя удалить, не удаляя подчинённый объект. Однако есть несколько подвидов зависимости, задаваемых в поле deptype:

DEPENDENCY_NORMAL (n)

Обычное отношение между отдельно создаваемыми объектами. Подчинённый объект можно удалить, не затрагивая вышестоящий объект. Вышестоящий объект можно удалить только с указанием CASCADE, при этом будет удалён и подчинённый объект. Например, столбец таблицы находится в обычной зависимости от своего типа данных.

DEPENDENCY_AUTO (a)

Подчинённый объект может быть удалён отдельно от вышестоящего и должен быть удалён автоматически (вне зависимости от указаний RESTRICT и CASCADE), если удаляется вышестоящий объект. Например, именованное ограничение для таблицы находится в автоматической зависимости от таблицы, так что оно исчезнет при удалении таблицы.

DEPENDENCY_INTERNAL (i)

Подчинённый объект был создан в процессе создания вышестоящего и на самом деле является только частью его внутренней реализации. Для такого объекта будет запрещена команда DROP (мы подскажем пользователю, что вместо этого надо выполнить DROP вышестоящий объект). Действие DROP для вышестоящего объекта будет распространено и на этот подчинённый объект, вне зависимости от присутствия указания CASCADE. Например, триггер, созданный для обеспечения ограничения внешнего ключа, становится внутренне зависимым от записи ограничения в pg_constraint.

DEPENDENCY_INTERNAL_AUTO (I)

Подчинённый объект был создан в процессе создания вышестоящего и на самом деле является только частью его внутренней реализации. Для такого объекта будет запрещена команда DROP (мы подскажем пользователю, что вместо неё надо выполнить DROP для вышестоящего объекта). Тогда как обычная внутренняя зависимость не позволит удалить зависимый объект, пока существуют такие зависимости, с DEPENDENCY_INTERNAL_AUTO будет выполнено удаление объектов, которые могут найтись по цепочке этих зависимостей. Например, индекс в секции становится автоматически внутренне зависимым и от самой секции, и от индекса родительской секционированной таблицы; поэтому секционированный индекс удаляется вместе с секцией, которую он индексирует, либо с родительским индексом, к которому он присоединён.

DEPENDENCY_EXTENSION (e)

Подчинённый объект входит в состав расширения, которое является вышестоящим объектом (см. pg_extension). Удалить подчинённый объект можно, только выполнив команду DROP EXTENSION для вышестоящего объекта. Функционально этот тип зависимости действует так же, как и внутренняя зависимость, но он выделен для наглядности и упрощения pg_dump.

DEPENDENCY_AUTO_EXTENSION (x)

Подчинённый объект не входит в состав расширения, которое является вышестоящим объектом (и поэтому не должен игнорироваться утилитой pg_dump), но не может функционировать без него, и поэтому должен удаляться при удалении расширения. При этом подчинённый объект может быть удалён и сам по себе.

DEPENDENCY_PIN (p)

Зависимый объект отсутствует; этот тип записи показывает, что система сама зависит от вышестоящего объекта, так что этот объект нельзя удалять ни при каких условиях. Записи этого типа создаются только командой initdb. Поля зависимого объекта в такой записи содержат нули.

В будущем могут появиться и другие подвиды зависимости.

52.18. pg_depend

The catalog pg_depend records the dependency relationships between database objects. This information allows DROP commands to find which other objects must be dropped by DROP CASCADE or prevent dropping in the DROP RESTRICT case.

See also pg_shdepend, which performs a similar function for dependencies involving objects that are shared across a database cluster.

Table 52.18. pg_depend Columns

NameTypeReferencesDescription
classidoidpg_class.oidThe OID of the system catalog the dependent object is in
objidoidany OID columnThe OID of the specific dependent object
objsubidint4  For a table column, this is the column number (the objid and classid refer to the table itself). For all other object types, this column is zero.
refclassidoidpg_class.oidThe OID of the system catalog the referenced object is in
refobjidoidany OID columnThe OID of the specific referenced object
refobjsubidint4  For a table column, this is the column number (the refobjid and refclassid refer to the table itself). For all other object types, this column is zero.
deptypechar  A code defining the specific semantics of this dependency relationship; see text

In all cases, a pg_depend entry indicates that the referenced object cannot be dropped without also dropping the dependent object. However, there are several subflavors identified by deptype:

DEPENDENCY_NORMAL (n)

A normal relationship between separately-created objects. The dependent object can be dropped without affecting the referenced object. The referenced object can only be dropped by specifying CASCADE, in which case the dependent object is dropped, too. Example: a table column has a normal dependency on its data type.

DEPENDENCY_AUTO (a)

The dependent object can be dropped separately from the referenced object, and should be automatically dropped (regardless of RESTRICT or CASCADE mode) if the referenced object is dropped. Example: a named constraint on a table is made autodependent on the table, so that it will go away if the table is dropped.

DEPENDENCY_INTERNAL (i)

The dependent object was created as part of creation of the referenced object, and is really just a part of its internal implementation. A DROP of the dependent object will be disallowed outright (we'll tell the user to issue a DROP against the referenced object, instead). A DROP of the referenced object will be propagated through to drop the dependent object whether CASCADE is specified or not. Example: a trigger that's created to enforce a foreign-key constraint is made internally dependent on the constraint's pg_constraint entry.

DEPENDENCY_INTERNAL_AUTO (I)

The dependent object was created as part of creation of the referenced object, and is really just a part of its internal implementation. A DROP of the dependent object will be disallowed outright (we'll tell the user to issue a DROP against the referenced object, instead). While a regular internal dependency will prevent the dependent object from being dropped while any such dependencies remain, DEPENDENCY_INTERNAL_AUTO will allow such a drop as long as the object can be found by following any of such dependencies. Example: an index on a partition is made internal-auto-dependent on both the partition itself as well as on the index on the parent partitioned table; so the partition index is dropped together with either the partition it indexes, or with the parent index it is attached to.

DEPENDENCY_EXTENSION (e)

The dependent object is a member of the extension that is the referenced object (see pg_extension). The dependent object can be dropped only via DROP EXTENSION on the referenced object. Functionally this dependency type acts the same as an internal dependency, but it's kept separate for clarity and to simplify pg_dump.

DEPENDENCY_AUTO_EXTENSION (x)

The dependent object is not a member of the extension that is the referenced object (and so should not be ignored by pg_dump), but cannot function without it and should be dropped when the extension itself is. The dependent object may be dropped on its own as well.

DEPENDENCY_PIN (p)

There is no dependent object; this type of entry is a signal that the system itself depends on the referenced object, and so that object must never be deleted. Entries of this type are created only by initdb. The columns for the dependent object contain zeroes.

Other dependency flavors might be needed in future.