50.18. pg_depend
В каталоге pg_depend записываются отношения зависимости между объектами базы данных. Благодаря этой информации, команды DROP могут найти, какие объекты должны удаляться при использовании DROP CASCADE, или когда нужно запрещать удаление при DROP RESTRICT.
Также смотрите описание каталога pg_shdepend, который играет подобную роль в отношении совместно используемых объектов в кластере баз данных.
Таблица 50.18. Столбцы pg_depend
| Имя | Тип | Ссылки | Описание |
|---|---|---|---|
classid | oid | | OID системного каталога, в котором находится зависимый объект |
objid | oid | любой столбец OID | OID определённого зависимого объекта |
objsubid | int4 | Для столбца таблицы это номер столбца (objid и classid указывают на саму таблицу). Для всех других типов объектов это поле содержит ноль. | |
refclassid | oid | | OID системного каталога, в котором находится вышестоящий объект |
refobjid | oid | любой столбец OID | OID определённого вышестоящего объекта |
refobjsubid | int4 | Для столбца таблицы это номер столбца (refobjid и refclassid указывают на саму таблицу). Для всех других типов объектов это поле содержит ноль. | |
deptype | char | Код, определяющий конкретную семантику данного отношения зависимости; см. текст |
Во всех случаях, запись в pg_depend показывает, что вышестоящий объект нельзя удалить, не удаляя подчинённый объект. Однако есть несколько подвидов зависимости, задаваемых в поле deptype:
DEPENDENCY_NORMAL(n)Обычное отношение между отдельно создаваемыми объектами. Подчинённый объект можно удалить, не затрагивая вышестоящий объект. Вышестоящий объект можно удалить только с указанием
CASCADE, при этом будет удалён и подчинённый объект. Например, столбец таблицы находится в обычной зависимости от своего типа данных.DEPENDENCY_AUTO(a)Подчинённый объект может быть удалён отдельно от вышестоящего и должен быть удалён автоматически (вне зависимости от указаний
RESTRICTиCASCADE), если удаляется вышестоящий объект. Например, именованное ограничение для таблицы находится в автоматической зависимости от таблицы, так что оно исчезнет при удалении таблицы.DEPENDENCY_INTERNAL(i)Подчинённый объект был создан в процессе создания вышестоящего и на самом деле является только частью его внутренней реализации. Для такого объекта будет запрещена команда
DROP(мы подскажем пользователю, что вместо этого надо выполнитьDROPвышестоящий объект). ДействиеDROPдля вышестоящего объекта будет распространено и на этот подчинённый объект, вне зависимости от присутствия указанияCASCADE. Например, триггер, созданный для обеспечения ограничения внешнего ключа, становится внутренне зависимым от записи ограничения вpg_constraint.DEPENDENCY_EXTENSION(e)Подчинённый объект входит в состав расширения, которое является вышестоящим объектом (см.
pg_extension). Удалить подчинённый объект можно, только выполнив командуDROP EXTENSIONдля вышестоящего объекта. Функционально этот тип зависимости действует так же, как и внутренняя зависимость, но он выделен для наглядности и упрощения pg_dump.DEPENDENCY_AUTO_EXTENSION(x)Подчинённый объект не входит в состав расширения, которое является вышестоящим объектом (и поэтому не должен игнорироваться утилитой pg_dump), но не может функционировать без него, и поэтому должен удаляться при удалении расширения. При этом подчинённый объект может быть удалён и сам по себе.
DEPENDENCY_PIN(p)Зависимый объект отсутствует; этот тип записи показывает, что система сама зависит от вышестоящего объекта, так что этот объект нельзя удалять ни при каких условиях. Записи этого типа создаются только командой
initdb. Поля зависимого объекта в такой записи содержат нули.
В будущем могут появиться и другие подвиды зависимости.
50.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 50.18. pg_depend Columns
| Name | Type | References | Description |
|---|---|---|---|
classid | oid | | The OID of the system catalog the dependent object is in |
objid | oid | any OID column | The OID of the specific dependent object |
objsubid | int4 | 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. | |
refclassid | oid | | The OID of the system catalog the referenced object is in |
refobjid | oid | any OID column | The OID of the specific referenced object |
refobjsubid | int4 | 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. | |
deptype | char | 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
RESTRICTorCASCADEmode) 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
DROPof the dependent object will be disallowed outright (we'll tell the user to issue aDROPagainst the referenced object, instead). ADROPof the referenced object will be propagated through to drop the dependent object whetherCASCADEis specified or not. Example: a trigger that's created to enforce a foreign-key constraint is made internally dependent on the constraint'spg_constraintentry.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 viaDROP EXTENSIONon 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.