51.18. pg_depend
В каталоге pg_depend
записываются отношения зависимости между объектами базы данных. Благодаря этой информации, команды DROP
могут найти, какие объекты должны удаляться при использовании DROP CASCADE
, или когда нужно запрещать удаление при DROP RESTRICT
.
Также смотрите описание каталога pg_shdepend
, который играет подобную роль в отношении совместно используемых объектов в кластере баз данных.
Таблица 51.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
. Поля зависимого объекта в такой записи содержат нули.
В будущем могут появиться и другие подвиды зависимости.
42.9. Errors and Messages
42.9.1. Reporting Errors and Messages
Use the RAISE
statement to report messages and raise errors.
RAISE [level
] 'format
' [,expression
[, ... ]] [ USINGoption
=expression
[, ... ] ]; RAISE [level
]condition_name
[ USINGoption
=expression
[, ... ] ]; RAISE [level
] SQLSTATE 'sqlstate
' [ USINGoption
=expression
[, ... ] ]; RAISE [level
] USINGoption
=expression
[, ... ]; RAISE ;
The level
option specifies the error severity. Allowed levels are DEBUG
, LOG
, INFO
, NOTICE
, WARNING
, and EXCEPTION
, with EXCEPTION
being the default. EXCEPTION
raises an error (which normally aborts the current transaction); the other levels only generate messages of different priority levels. Whether messages of a particular priority are reported to the client, written to the server log, or both is controlled by the log_min_messages and client_min_messages configuration variables. See Chapter 19 for more information.
After level
if any, you can specify a format
string (which must be a simple string literal, not an expression). The format string specifies the error message text to be reported. The format string can be followed by optional argument expressions to be inserted into the message. Inside the format string, %
is replaced by the string representation of the next optional argument's value. Write %%
to emit a literal %
. The number of arguments must match the number of %
placeholders in the format string, or an error is raised during the compilation of the function.
In this example, the value of v_job_id
will replace the %
in the string:
RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
You can attach additional information to the error report by writing USING
followed by option
= expression
items. Each expression
can be any string-valued expression. The allowed option
key words are:
MESSAGE
Sets the error message text. This option can't be used in the form of
RAISE
that includes a format string beforeUSING
.DETAIL
Supplies an error detail message.
HINT
Supplies a hint message.
ERRCODE
Specifies the error code (SQLSTATE) to report, either by condition name, as shown in Appendix A, or directly as a five-character SQLSTATE code.
COLUMN
CONSTRAINT
DATATYPE
TABLE
SCHEMA
Supplies the name of a related object.
This example will abort the transaction with the given error message and hint:
RAISE EXCEPTION 'Nonexistent ID --> %', user_id USING HINT = 'Please check your user ID';
These two examples show equivalent ways of setting the SQLSTATE:
RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation'; RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
There is a second RAISE
syntax in which the main argument is the condition name or SQLSTATE to be reported, for example:
RAISE division_by_zero; RAISE SQLSTATE '22012';
In this syntax, USING
can be used to supply a custom error message, detail, or hint. Another way to do the earlier example is
RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
Still another variant is to write RAISE USING
or RAISE
and put everything else into the level
USINGUSING
list.
The last variant of RAISE
has no parameters at all. This form can only be used inside a BEGIN
block's EXCEPTION
clause; it causes the error currently being handled to be re-thrown.
Note
Before PostgreSQL 9.1, RAISE
without parameters was interpreted as re-throwing the error from the block containing the active exception handler. Thus an EXCEPTION
clause nested within that handler could not catch it, even if the RAISE
was within the nested EXCEPTION
clause's block. This was deemed surprising as well as being incompatible with Oracle's PL/SQL.
If no condition name nor SQLSTATE is specified in a RAISE EXCEPTION
command, the default is to use raise_exception
(P0001
). If no message text is specified, the default is to use the condition name or SQLSTATE as message text.
Note
When specifying an error code by SQLSTATE code, you are not limited to the predefined error codes, but can select any error code consisting of five digits and/or upper-case ASCII letters, other than 00000
. It is recommended that you avoid throwing error codes that end in three zeroes, because these are category codes and can only be trapped by trapping the whole category.
42.9.2. Checking Assertions
The ASSERT
statement is a convenient shorthand for inserting debugging checks into PL/pgSQL functions.
ASSERTcondition
[ ,message
];
The condition
is a Boolean expression that is expected to always evaluate to true; if it does, the ASSERT
statement does nothing further. If the result is false or null, then an ASSERT_FAILURE
exception is raised. (If an error occurs while evaluating the condition
, it is reported as a normal error.)
If the optional message
is provided, it is an expression whose result (if not null) replaces the default error message text “assertion failed”, should the condition
fail. The message
expression is not evaluated in the normal case where the assertion succeeds.
Testing of assertions can be enabled or disabled via the configuration parameter plpgsql.check_asserts
, which takes a Boolean value; the default is on
. If this parameter is off
then ASSERT
statements do nothing.
Note that ASSERT
is meant for detecting program bugs, not for reporting ordinary error conditions. Use the RAISE
statement, described above, for that.