51.7. pg_attribute
В каталоге pg_attribute
хранится информация о столбцах таблицы. Для каждого столбца каждой таблицы в pg_attribute
существует ровно одна строка. (Также в этом каталоге будут записи для индексов и на самом деле для всех объектов, присутствующих в pg_class
.)
Термин «атрибут» равнозначен «столбцу» и употребляется по историческим причинам.
Таблица 51.7. Столбцы pg_attribute
Имя | Тип | Ссылки | Описание |
---|---|---|---|
attrelid | oid |
| Таблица, к которой принадлежит столбец |
attname | name | Имя столбца | |
atttypid | oid |
| Тип данных этого столбца |
attstattarget | int4 | Столбец attstattarget управляет детализацией статистики, собираемой по этому столбцу командой ANALYZE. Нулевое значение указывает, что статистика не собирается. При отрицательном значении используется системное ограничение статистики по умолчанию. Точное значение положительных величин определяется типом данных. Для скалярных типов данных, attstattarget задаёт и целевое число собираемых «самых частых значений», и целевое число создаваемых групп гистограммы. | |
attlen | int2 | Копия pg_type.typlen из записи типа столбца | |
attnum | int2 | Порядковый номер столбца. Обычные столбцы нумеруются по возрастанию, начиная с 1. Системные столбцы, такие как oid , имеют (обычно) отрицательные номера. | |
attndims | int4 | Число размерностей, если столбец имеет тип массива; ноль в противном случае. (В настоящее время число размерностей массива не контролируется, поэтому любое ненулевое значение по сути означает «это массив».) | |
attcacheoff | int4 | Всегда -1 в постоянном хранилище, но когда запись загружается в память, в этом поле может кешироваться смещение атрибута в строке | |
atttypmod | int4 | В поле atttypmod записывается дополнительное число, связанное с определённым типом данных, указываемое при создании таблицы (например, максимальный размер столбца varchar ). Это значение передаётся функциям ввода и преобразования длины конкретного типа. Для типов, которым не нужен atttypmod , это обычно -1. | |
attbyval | bool | Копия pg_type.typbyval из записи типа столбца | |
attstorage | char | Обычно копия pg_type.typstorage из записи типа столбца. Для типов, поддерживающих TOAST, можно изменять это значение после создания столбца и таким образом управлять политикой хранения. | |
attalign | char | Копия pg_type.typalign из записи типа столбца | |
attnotnull | bool | Представляет ограничение NOT NULL. | |
atthasdef | bool | Столбец имеет значение по умолчанию, в этом случае в каталоге pg_attrdef будет соответствующая запись, определяющая это значение. | |
attidentity | char | Пустой символ ('' ) указывает, что это не столбец идентификации. Символ a указывает, что значение генерируется всегда, а d — что значение генерируется по умолчанию. | |
attisdropped | bool | Столбец был удалён и теперь не является рабочим. Удалённый столбец может по-прежнему физически присутствовать в таблице, но анализатор запросов его игнорирует, так что обратиться к нему из SQL нельзя. | |
attislocal | bool | Столбец определён локально в данном отношении. Заметьте, что столбец может быть определён локально и при этом наследоваться. | |
attinhcount | int4 | Число прямых предков этого столбца. Столбец с ненулевым числом предков нельзя удалить или переименовать. | |
attcollation | oid |
| Заданное для столбца правило сортировки, либо ноль, если тип столбца не сортируемый. |
attacl | aclitem[] | Права доступа к столбцу, если они были заданы непосредственно для этого столбца | |
attoptions | text[] | Параметры уровня атрибута, в виде строк «ключ=значение» | |
attfdwoptions | text[] | Параметры уровня атрибута для обёрток сторонних данных, в виде строк «ключ=значение» |
В записи удалённого столбца в pg_attribute
поле atttypid
сбрасывается в ноль, но attlen
и другие поля, копируемые из pg_type
, сохраняют актуальные значения. Это нужно, чтобы справиться с ситуацией, когда после удаления столбца удаляется и его тип данных, так что записи в pg_type
больше не будет. В таких случаях для интерпретации содержимого строки таблицы могут использоваться attlen
и другие поля.
51.7. pg_attribute
The catalog pg_attribute
stores information about table columns. There will be exactly one pg_attribute
row for every column in every table in the database. (There will also be attribute entries for indexes, and indeed all objects that have pg_class
entries.)
The term attribute is equivalent to column and is used for historical reasons.
Table 51.7. pg_attribute
Columns
Name | Type | References | Description |
---|---|---|---|
attrelid | oid |
| The table this column belongs to |
attname | name | The column name | |
atttypid | oid |
| The data type of this column |
attstattarget | int4 | attstattarget controls the level of detail of statistics accumulated for this column by ANALYZE. A zero value indicates that no statistics should be collected. A negative value says to use the system default statistics target. The exact meaning of positive values is data type-dependent. For scalar data types, attstattarget is both the target number of “most common values” to collect, and the target number of histogram bins to create. | |
attlen | int2 | A copy of pg_type.typlen of this column's type | |
attnum | int2 | The number of the column. Ordinary columns are numbered from 1 up. System columns, such as oid , have (arbitrary) negative numbers. | |
attndims | int4 | Number of dimensions, if the column is an array type; otherwise 0. (Presently, the number of dimensions of an array is not enforced, so any nonzero value effectively means “it's an array”.) | |
attcacheoff | int4 | Always -1 in storage, but when loaded into a row descriptor in memory this might be updated to cache the offset of the attribute within the row | |
atttypmod | int4 | atttypmod records type-specific data supplied at table creation time (for example, the maximum length of a varchar column). It is passed to type-specific input functions and length coercion functions. The value will generally be -1 for types that do not need atttypmod . | |
attbyval | bool | A copy of pg_type.typbyval of this column's type | |
attstorage | char | Normally a copy of pg_type.typstorage of this column's type. For TOAST-able data types, this can be altered after column creation to control storage policy. | |
attalign | char | A copy of pg_type.typalign of this column's type | |
attnotnull | bool | This represents a not-null constraint. | |
atthasdef | bool | This column has a default value, in which case there will be a corresponding entry in the pg_attrdef catalog that actually defines the value. | |
attidentity | char | If a zero byte ('' ), then not an identity column. Otherwise, a = generated always, d = generated by default. | |
attisdropped | bool | This column has been dropped and is no longer valid. A dropped column is still physically present in the table, but is ignored by the parser and so cannot be accessed via SQL. | |
attislocal | bool | This column is defined locally in the relation. Note that a column can be locally defined and inherited simultaneously. | |
attinhcount | int4 | The number of direct ancestors this column has. A column with a nonzero number of ancestors cannot be dropped nor renamed. | |
attcollation | oid |
| The defined collation of the column, or zero if the column is not of a collatable data type. |
attacl | aclitem[] | Column-level access privileges, if any have been granted specifically on this column | |
attoptions | text[] | Attribute-level options, as “keyword=value” strings | |
attfdwoptions | text[] | Attribute-level foreign data wrapper options, as “keyword=value” strings |
In a dropped column's pg_attribute
entry, atttypid
is reset to zero, but attlen
and the other fields copied from pg_type
are still valid. This arrangement is needed to cope with the situation where the dropped column's data type was later dropped, and so there is no pg_type
row anymore. attlen
and the other fields can be used to interpret the contents of a row of the table.