53.13. pg_constraint #

В каталоге pg_constraint хранятся ограничения-проверки, ограничения-исключения, а также ограничения первичного ключа, уникальности и внешних ключей, определённые для таблиц. (Ограничения столбцов описываются как и все остальные. Любое ограничение столбца равнозначно некоторому ограничению таблицы.) Ограничения на NULL представляются не здесь, а в каталоге pg_attribute.

Для пользовательских триггеров ограничений (создаваемых командой CREATE CONSTRAINT TRIGGER) в этой таблице также создаётся запись.

Здесь также хранятся ограничения доменов.

Таблица 53.13. Столбцы pg_constraint

Тип столбца

Описание

oid oid

Идентификатор строки

conname name

Имя ограничения (не обязательно уникальное!)

connamespace oid (ссылается на pg_namespace.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 (ссылается на pg_class.oid)

Таблица, для которой установлено это ограничение; ноль, если это не ограничение таблицы

contypid oid (ссылается на pg_type.oid)

Домен, к которому относится это ограничение; ноль, если это не ограничение домена

conindid oid (ссылается на pg_class.oid)

Индекс, поддерживающий это ограничение, если это ограничение уникальности, первичного или внешнего ключа, либо ограничение-исключение; в противном случае — ноль

conparentid oid (ссылается на pg_constraint.oid)

Соответствующее ограничение в родительской секционированной таблице, если это ограничение в секции; иначе ноль

confrelid oid (ссылается на pg_class.oid)

Если это внешний ключ, таблица, на которую он ссылается; иначе ноль

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 int2

Число прямых предков этого ограничения. Ограничение с ненулевым числом предков нельзя удалить или переименовать.

connoinherit bool

Ограничение определено локально для данного отношения и является ненаследуемым.

conkey int2[] (ссылается на pg_attribute.attnum)

Для ограничений таблицы (включая внешние ключи, но не триггеры ограничений), определяет список столбцов, образующих ограничение

confkey int2[] (ссылается на pg_attribute.attnum)

Для внешнего ключа определяет список столбцов, на которые он ссылается

conpfeqop oid[] (ссылается на pg_operator.oid)

Для внешнего ключа — список операторов равенства для сравнений PK = FK

conppeqop oid[] (ссылается на pg_operator.oid)

Для внешнего ключа — список операторов равенства для сравнений PK = PK

conffeqop oid[] (ссылается на pg_operator.oid)

Для внешнего ключа — список операторов равенства для сравнений FK = FK

confdelsetcols int2[] (ссылается на pg_attribute.attnum)

Для внешнего ключа с указанием SET NULL или SET DEFAULT при удалении — список изменяемых столбцов. Значение NULL показывает, что изменены будут все столбцы, на которые ссылается ключ.

conexclop oid[] (ссылается на pg_operator.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

Column Type

Description

oid oid

Row identifier

conname name

Constraint name (not necessarily unique!)

connamespace oid (references pg_namespace.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 be false only for foreign keys and CHECK constraints

conrelid oid (references pg_class.oid)

The table this constraint is on; zero if not a table constraint

contypid oid (references pg_type.oid)

The domain this constraint is on; zero if not a domain constraint

conindid oid (references pg_class.oid)

The index supporting this constraint, if it's a unique, primary key, foreign key, or exclusion constraint; else zero

conparentid oid (references pg_constraint.oid)

The corresponding constraint of the parent partitioned table, if this is a constraint on a partition; else zero

confrelid oid (references pg_class.oid)

If a foreign key, the referenced table; else zero

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 int2

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[] (references pg_attribute.attnum)

If a table constraint (including foreign keys, but not constraint triggers), list of the constrained columns

confkey int2[] (references pg_attribute.attnum)

If a foreign key, list of the referenced columns

conpfeqop oid[] (references pg_operator.oid)

If a foreign key, list of the equality operators for PK = FK comparisons

conppeqop oid[] (references pg_operator.oid)

If a foreign key, list of the equality operators for PK = PK comparisons

conffeqop oid[] (references pg_operator.oid)

If a foreign key, list of the equality operators for FK = FK comparisons

confdelsetcols int2[] (references pg_attribute.attnum)

If a foreign key with a SET NULL or SET DEFAULT delete action, the columns that will be updated. If null, all of the referencing columns will be updated.

conexclop oid[] (references pg_operator.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.