10.4. Хранимое значение #
Значения, вставляемые в таблицу, преобразуется в тип данных целевого столбца по следующему алгоритму.
Преобразование по типу хранения
Проверить точное совпадение с целевым типом.
Если типы не совпадают, попытаться привести тип к целевому. Это возможно, если в каталоге
pg_cast(см. CREATE CAST) зарегистрировано приведение присваивания между двумя типами. Если же результат выражения — строка неизвестного типа, содержимое этой строки будет подано на вход процедуре ввода целевого типа.Проверить, не требуется ли приведение размера для целевого типа. Приведение размера — это преобразование типа к такому же. Если это приведение описано в каталоге
pg_cast, применить к его к результату выражения, прежде чем сохранить в целевом столбце. Функция, реализующая такое приведение, всегда принимает дополнительный параметр типаinteger, в котором передаётся значениеatttypmodдля целевого столбца (обычно это её объявленный размер, хотя интерпретироваться значениеatttypmodдля разных типов данных может по-разному), и третий параметр типаboolean, передающий признак явное/неявное преобразование. Функция приведения отвечает за все операции с длиной, включая её проверку и усечение данных.
Пример 10.9. Преобразование для типа хранения character
Следующие запросы показывают, что сохраняемое значение подгоняется под размер целевого столбца, объявленного как character(20):
CREATE TABLE vv (v character(20));
INSERT INTO vv SELECT 'abc' || 'def';
SELECT v, octet_length(v) FROM vv;
v | octet_length
----------------------+--------------
abcdef | 20
(1 row)
Суть происходящего здесь в том, что две константы неизвестного типа по умолчанию воспринимаются как значения text, что позволяет применить к ним оператор || как оператор конкатенации значений text. Затем результат оператора, имеющий тип text, приводится к типу bpchar («blank-padded char» (символы, дополненные пробелами), внутреннее имя типа character) в соответствии с типом целевого столбца. (Так как типы text и bpchar двоично-совместимы, при этом преобразовании реальный вызов функции не добавляется.) Наконец, в системном каталоге находится функция изменения размера bpchar(bpchar, integer, boolean) и применяется для результата оператора и длины столбца. Эта связанная с типом функция проверяет длину данных и добавляет недостающие пробелы.
10.4. Value Storage #
Values to be inserted into a table are converted to the destination column's data type according to the following steps.
Value Storage Type Conversion
Check for an exact match with the target.
Otherwise, try to convert the expression to the target type. This is possible if an assignment cast between the two types is registered in the
pg_castcatalog (see CREATE CAST). Alternatively, if the expression is an unknown-type literal, the contents of the literal string will be fed to the input conversion routine for the target type.Check to see if there is a sizing cast for the target type. A sizing cast is a cast from that type to itself. If one is found in the
pg_castcatalog, apply it to the expression before storing into the destination column. The implementation function for such a cast always takes an extra parameter of typeinteger, which receives the destination column'satttypmodvalue (typically its declared length, although the interpretation ofatttypmodvaries for different data types), and it may take a thirdbooleanparameter that says whether the cast is explicit or implicit. The cast function is responsible for applying any length-dependent semantics such as size checking or truncation.
Example 10.9. character Storage Type Conversion
For a target column declared as character(20) the following statement shows that the stored value is sized correctly:
CREATE TABLE vv (v character(20));
INSERT INTO vv SELECT 'abc' || 'def';
SELECT v, octet_length(v) FROM vv;
v | octet_length
----------------------+--------------
abcdef | 20
(1 row)
What has really happened here is that the two unknown literals are resolved to text by default, allowing the || operator to be resolved as text concatenation. Then the text result of the operator is converted to bpchar (“blank-padded char”, the internal name of the character data type) to match the target column type. (Since the conversion from text to bpchar is binary-coercible, this conversion does not insert any real function call.) Finally, the sizing function bpchar(bpchar, integer, boolean) is found in the system catalog and applied to the operator's result and the stored column length. This type-specific function performs the required length check and addition of padding spaces.