53.13. pg_constraint
В каталоге pg_constraint хранятся ограничения-проверки, ограничения-исключения, а также ограничения первичного ключа, уникальности и внешних ключей, определённые для таблиц. (Ограничения столбцов описываются как и все остальные. Любое ограничение столбца равнозначно некоторому ограничению таблицы.) Ограничения на NULL представляются не здесь, а в каталоге pg_attribute.
Для пользовательских триггеров ограничений (создаваемых командой CREATE CONSTRAINT TRIGGER) в этой таблице также создаётся запись.
Здесь также хранятся ограничения доменов.
Таблица 53.13. Столбцы pg_constraint
| Name | Тип | Ссылки | Описание |
|---|---|---|---|
oid | oid | Идентификатор строки | |
conname | name | Имя ограничения (не обязательно уникальное!) | |
connamespace | oid | | OID пространства имён, содержащего это ограничение |
contype | char | c = ограничение-проверка (check), f = внешний ключ (foreign key), p = первичный ключ (primary key), u = ограничение уникальности (unique), t = триггер ограничения (trigger), x = ограничение-исключение (exclusion) | |
condeferrable | bool | Является ли ограничение откладываемым? | |
condeferred | bool | Является ли ограничение отложенным по умолчанию? | |
convalidated | bool | Было ли ограничение проверено? В настоящее время значение false возможно только для внешних ключей и ограничений CHECK | |
conrelid | oid | | Таблица, для которой установлено это ограничение; 0, если это не ограничение таблицы |
contypid | oid | | Домен, к которому относится это ограничение; 0, если это не ограничение домена |
conindid | oid | | Индекс, поддерживающий это ограничение, если это ограничение уникальности, первичного или внешнего ключа, либо ограничение-исключение; в противном случае — 0 |
conparentid | oid | | Соответствующее ограничение в родительской секционированной таблице, если это ограничение в секции; иначе 0 |
confrelid | oid | | Если это внешний ключ, таблица, на которую он ссылается; иначе 0 |
confupdtype | char | Код действия при изменении внешнего ключа: a = нет действия, r = ограничить (restrict), c = каскадное действие (cascade), n = присвоить NULL, d = поведение по умолчанию | |
confdeltype | char | Код действия при удалении внешнего ключа: a = нет действия, r = ограничить (restrict), c = каскадное действие (cascade), n = присвоить NULL, d = поведение по умолчанию | |
confmatchtype | char | Тип сопоставления внешнего ключа: f = полное (full), p = частичное (partial), s = простое (simple) | |
conislocal | bool | Ограничение определено локально в данном отношении. Заметьте, что ограничение может быть определено локально и при этом наследоваться. | |
coninhcount | int4 | Число прямых предков этого ограничения. Ограничение с ненулевым числом предков нельзя удалить или переименовать. | |
connoinherit | bool | Ограничение определено локально для данного отношения и является ненаследуемым. | |
conkey | int2[] | | Для ограничений таблицы (включая внешние ключи, но не триггеры ограничений), определяет список столбцов, образующих ограничение |
confkey | int2[] | | Для внешнего ключа определяет список столбцов, на которые он ссылается |
conpfeqop | oid[] | | Для внешнего ключа — список операторов равенства для сравнений PK = FK |
conppeqop | oid[] | | Для внешнего ключа — список операторов равенства для сравнений PK = PK |
conffeqop | oid[] | | Для внешнего ключа — список операторов равенства для сравнений FK = FK |
conexclop | oid[] | | Для ограничения-исключения — список операторов исключения по столбцам |
conbin | pg_node_tree | Для ограничения-проверки — внутреннее представление выражения. (Чтобы извлечь определение ограничения-проверки, рекомендуется использовать pg_get_constraintdef().) |
В случае с ограничением-исключением значение conkey полезно только для элементов ограничений, представляющих простые ссылки на столбцы. Для других случаев в conkey задаётся ноль, и чтобы получить выражение, определяющее ограничение, надо обратиться к соответствующему индексу. (Таким образом, поле conkey имеет то же содержимое, что и pg_index.indkey для индекса.)
Примечание
Поле pg_class.relchecks должно согласовываться с числом ограничений-проверок, описанных в данной таблице для каждого отношения.
53.13. pg_constraint
The catalog pg_constraint stores check, primary key, unique, foreign key, and exclusion constraints on tables. (Column constraints are not treated specially. Every column constraint is equivalent to some table constraint.) Not-null constraints are represented in the pg_attribute catalog, not here.
User-defined constraint triggers (created with CREATE CONSTRAINT TRIGGER) also give rise to an entry in this table.
Check constraints on domains are stored here, too.
Table 53.13. pg_constraint Columns
| Name | Type | References | Description |
|---|---|---|---|
oid | oid | Row identifier | |
conname | name | Constraint name (not necessarily unique!) | |
connamespace | oid | | The OID of the namespace that contains this constraint |
contype | char | c = check constraint, f = foreign key constraint, p = primary key constraint, u = unique constraint, t = constraint trigger, x = exclusion constraint | |
condeferrable | bool | Is the constraint deferrable? | |
condeferred | bool | Is the constraint deferred by default? | |
convalidated | bool | Has the constraint been validated? Currently, can only be false for foreign keys and CHECK constraints | |
conrelid | oid | | The table this constraint is on; 0 if not a table constraint |
contypid | oid | | The domain this constraint is on; 0 if not a domain constraint |
conindid | oid | | The index supporting this constraint, if it's a unique, primary key, foreign key, or exclusion constraint; else 0 |
conparentid | oid | | The corresponding constraint in the parent partitioned table, if this is a constraint in a partition; else 0 |
confrelid | oid | | If a foreign key, the referenced table; else 0 |
confupdtype | char | Foreign key update action code: a = no action, r = restrict, c = cascade, n = set null, d = set default | |
confdeltype | char | Foreign key deletion action code: a = no action, r = restrict, c = cascade, n = set null, d = set default | |
confmatchtype | char | Foreign key match type: f = full, p = partial, s = simple | |
conislocal | bool | This constraint is defined locally for the relation. Note that a constraint can be locally defined and inherited simultaneously. | |
coninhcount | int4 | The number of direct inheritance ancestors this constraint has. A constraint with a nonzero number of ancestors cannot be dropped nor renamed. | |
connoinherit | bool | This constraint is defined locally for the relation. It is a non-inheritable constraint. | |
conkey | int2[] | | If a table constraint (including foreign keys, but not constraint triggers), list of the constrained columns |
confkey | int2[] | | If a foreign key, list of the referenced columns |
conpfeqop | oid[] | | If a foreign key, list of the equality operators for PK = FK comparisons |
conppeqop | oid[] | | If a foreign key, list of the equality operators for PK = PK comparisons |
conffeqop | oid[] | | If a foreign key, list of the equality operators for FK = FK comparisons |
conexclop | oid[] | | If an exclusion constraint, list of the per-column exclusion operators |
conbin | pg_node_tree | If a check constraint, an internal representation of the expression. (It's recommended to use pg_get_constraintdef() to extract the definition of a check constraint.) |
In the case of an exclusion constraint, conkey is only useful for constraint elements that are simple column references. For other cases, a zero appears in conkey and the associated index must be consulted to discover the expression that is constrained. (conkey thus has the same contents as pg_index.indkey for the index.)
Note
pg_class.relchecks needs to agree with the number of check-constraint entries found in this table for each relation.