9.5. Функции и операторы двоичных строк

В этом разделе описываются функции и операторы для работы с двоичными строками, то есть со значениями типа bytea. Многие из них идентичны по функциональности и синтаксису описанным в предыдущем разделе функциям, предназначенным для текстовых строк.

В SQL определены несколько строковых функций, в которых аргументы разделяются не запятыми, а ключевыми словами. Подробнее это описано в Таблице 9.11. Postgres Pro также предоставляет варианты этих функций с синтаксисом, обычным для функций (см. Таблицу 9.12).

Таблица 9.11. SQL-функции и операторы для работы с двоичными строками

Функция/оператор

Описание

Пример(ы)

bytea || byteabytea

Соединяет две двоичные строки.

'\x123456'::bytea || '\x789a00bcde'::bytea\x123456789a00bcde

bit_length ( bytea ) → integer

Возвращает число бит в двоичной строке (это число в 8 раз больше octet_length).

bit_length('\x123456'::bytea)24

octet_length ( bytea ) → integer

Возвращает число байт в двоичной строке.

octet_length('\x123456'::bytea)3

overlay ( bytes bytea PLACING newsubstring bytea FROM start integer [FOR count integer] ) → bytea

Заменяет подстроку в bytes, начиная с байта с номером start, длиной count байт, на подстроку newsubstring. В отсутствие параметра count количество заменяемых байтов определяется длиной newsubstring.

overlay('\x1234567890'::bytea placing '\002\003'::bytea from 2 for 3)\x12020390

position ( substring bytea IN bytes bytea ) → integer

Возвращает начальную позицию первого вхождения substring в bytes либо 0, если такого вхождения нет.

position('\x5678'::bytea in '\x1234567890'::bytea)3

substring ( bytes bytea [FROM start integer] [FOR count integer] ) → bytea

Извлекает из bytes подстроку, начиная с позиции start (если она указана), длиной до count символов (если она указана). Параметры start и count могут опускаться, но не оба сразу.

substring('\x1234567890'::bytea from 3 for 2)\x5678

trim ( [BOTH] bytesremoved bytea FROM bytes bytea ) → bytea

Удаляет наибольшую строку, содержащую только байты, заданные в параметре bytesremoved, с начала и с конца строки bytes.

trim('\x9012'::bytea from '\x1234567890'::bytea)\x345678

trim ( [BOTH] [FROM] bytes bytea, bytesremoved bytea ) → bytea

Это нестандартный синтаксис вызова trim().

trim(both from '\x1234567890'::bytea, '\x9012'::bytea)\x345678


В PostgreSQL есть и другие функции для работы с двоичными строками, перечисленные в Таблице 9.12. Некоторые из них используются в качестве внутренней реализации стандартных функций SQL, приведённых в Таблице 9.11.

Таблица 9.12. Другие функции для работы с двоичными строками

Функция

Описание

Пример(ы)

btrim ( bytes bytea, bytesremoved bytea ) → bytea

Удаляет наибольшую строку, содержащую только байты, заданные в параметре bytesremoved, с начала и с конца строки bytes.

btrim('\x1234567890'::bytea, '\x9012'::bytea)\x345678

get_bit ( bytes bytea, n bigint ) → integer

Извлекает из двоичной строки бит с номером n.

get_bit('\x1234567890'::bytea, 30)1

get_byte ( bytes bytea, n integer ) → integer

Извлекает из двоичной строки байт с номером n.

get_byte('\x1234567890'::bytea, 4)144

length ( bytea ) → integer

Выдаёт число байт в двоичной строке.

length('\x1234567890'::bytea)5

length ( bytes bytea, encoding name ) → integer

Выдаёт число символов в двоичной строке, в предположении, что она содержит текст в кодировке encoding.

length('jose'::bytea, 'UTF8')4

md5 ( bytea ) → text

Вычисляет MD5-хеш двоичной строки и выдаёт результат в шестнадцатеричном виде.

md5('Th\000omas'::bytea)8ab2d3c9689aaf18​b4958c334c82d8b1

set_bit ( bytes bytea, n bigint, newvalue integer ) → bytea

Устанавливает в двоичной строке для бита с номером n значение newvalue.

set_bit('\x1234567890'::bytea, 30, 0)\x1234563890

set_byte ( bytes bytea, n integer, newvalue integer ) → bytea

Устанавливает в двоичной строке для байта с номером n значение newvalue.

set_byte('\x1234567890'::bytea, 4, 64)\x1234567840

sha224 ( bytea ) → bytea

Вычисляет хеш SHA-224 для двоичной строки.

sha224('abc'::bytea)\x23097d223405d8228642a477bda2​55b32aadbce4bda0b3f7e36c9da7

sha256 ( bytea ) → bytea

Вычисляет хеш SHA-256 для двоичной строки.

sha256('abc'::bytea)\xba7816bf8f01cfea414140de5dae2223​b00361a396177a9cb410ff61f20015ad

sha384 ( bytea ) → bytea

Вычисляет хеш SHA-384 для двоичной строки.

sha384('abc'::bytea)\xcb00753f45a35e8bb5a03d699ac65007​272c32ab0eded1631a8b605a43ff5bed​8086072ba1e7cc2358baeca134c825a7

sha512 ( bytea ) → bytea

Вычисляет хеш SHA-512 для двоичной строки.

sha512('abc'::bytea)\xddaf35a193617abacc417349ae204131​12e6fa4e89a97ea20a9eeee64b55d39a​2192992a274fc1a836ba3c23a3feebbd​454d4423643ce80e2a9ac94fa54ca49f

substr ( bytes bytea, start integer [, count integer] ) → bytea

Извлекает из bytes подстроку, начиная с позиции start, длиной до count байт (если это значение указано). (Ей равнозначна функция substring(bytes from start for count).)

substr('\x1234567890'::bytea, 3, 2)\x5678


Для функций get_byte и set_byte байты нумеруется с 0. Функции get_bit и set_bit нумеруют биты справа налево; например, бит 0 будет меньшим значащим битом первого байта, а бит 15 — большим значащим битом второго байта.

По историческим причинам функция md5 возвращает значение в шестнадцатеричном виде в типе text, тогда как функции SHA-2 возвращают тип bytea. Для преобразования значения из одного представления в другое используйте функции encode и decode. Например, вызвав encode(sha256('abc'), 'hex'), вы получите значение в шестнадцатеричном виде в текстовой строке, а decode(md5('abc'), 'hex') выдаст значение bytea.

В Таблице 9.13 показаны функции для перекодирования текста из одного набора символов (кодировки) в другой и для представления произвольных двоичных данных в текстовом виде. Для всех этих функций аргумент или результат типа text содержит текст в текущей кодировке базы данных, тогда как аргументы или результаты типа bytea содержат текст в кодировке, заданной соответствующим аргументом.

Таблица 9.13. Функции для преобразования текстовых/двоичных строк

Функция

Описание

Пример(ы)

convert ( bytes bytea, src_encoding name, dest_encoding name ) → bytea

Преобразует двоичную строку, содержащую текст в кодировке src_encoding, в двоичную строку с текстом в кодировке dest_encoding (возможные варианты преобразований описаны в Подразделе 23.3.4).

convert('text_in_utf8'​, 'UTF8', 'LATIN1')\x746578745f696e5f75746638

convert_from ( bytes bytea, src_encoding name ) → text

Преобразует двоичную строку, содержащую текст в кодировке src_encoding, в строку типа text в кодировке базы данных (возможные варианты преобразований описаны в Подразделе 23.3.4).

convert_from('text_in_utf8'​, 'UTF8')text_in_utf8

convert_to ( string text, dest_encoding name ) → bytea

Преобразует строку типа text в кодировке базы данных в двоичную строку с текстом в кодировке dest_encoding (возможные варианты преобразований описаны в Подразделе 23.3.4).

convert_to('некоторый_текст', 'UTF8')\x736f6d655f74657874

encode ( bytes bytea, format text ) → text

Переводит двоичные данные в текстовое представление; поддерживаются следующие значения format: base64, escape, hex.

encode('123\000\001', 'base64')MTIzAAE=

decode ( string text, format text ) → bytea

Переводит двоичные данные из текстового представления; поддерживает те же значения format, что и функция encode.

decode('MTIzAAE=', 'base64')\x3132330001


Функции encode и decode поддерживают следующие текстовые форматы:

base64

Формат base64 описан в RFC 2045, Разделе 6.8. Согласно этому RFC, закодированные строки разбиваются по 76 символов. Однако завершаются строки не символами CRLF (как требуется в соответствии с MIME), а одним символом конца строки. Функция decode, с другой стороны, игнорирует символы перевода каретки, новой строки, пробелы и табуляции. Если на вход decode поступают некорректные данные base64, возникает ошибка — в том числе, если оказывается некорректным завершающее выравнивание.

escape

В формате escape нулевые байты и байты с установленным старшим битом переводятся в восьмеричные спецпоследовательности (\nnn), а обратная косая черта дублируется. Другие байтовые значения представляются в буквальном виде. Функция decode выдаст ошибку, встретив обратную косую черту, за которой не следует ещё одна обратная косая или три восьмеричных цифры; другие значения байта она принимает без изменений.

hex

В формате hex каждые 4 бита данных представляются одной шестнадцатеричной цифрой, от 0 до f, при этом первой идёт цифра, представляющая старшие биты. Шестнадцатеричные цифры a-f функция encode выводит в нижнем регистре. Так как наименьшая единица данных — байт (8 бит), функция encode всегда возвращает чётное количество символов. Функция decode, с другой стороны, принимает символы a-f в любом регистре. Если на вход функции decode поступают некорректные данные, возникает ошибка — в том числе, если число символов оказывается нечётным.

См. также агрегатную функцию string_agg в Разделе 9.21 и функции для работы с большими объектами в Разделе 37.4.

36.2. The Postgres Pro Type System

Postgres Pro data types can be divided into base types, container types, domains, and pseudo-types.

36.2.1. Base Types

Base types are those, like integer, that are implemented below the level of the SQL language (typically in a low-level language such as C). They generally correspond to what are often known as abstract data types. Postgres Pro can only operate on such types through functions provided by the user and only understands the behavior of such types to the extent that the user describes them. The built-in base types are described in Chapter 8.

Enumerated (enum) types can be considered as a subcategory of base types. The main difference is that they can be created using just SQL commands, without any low-level programming. Refer to Section 8.7 for more information.

36.2.2. Container Types

Postgres Pro has three kinds of container types, which are types that contain multiple values of other types. These are arrays, composites, and ranges.

Arrays can hold multiple values that are all of the same type. An array type is automatically created for each base type, composite type, range type, and domain type. But there are no arrays of arrays. So far as the type system is concerned, multi-dimensional arrays are the same as one-dimensional arrays. Refer to Section 8.15 for more information.

Composite types, or row types, are created whenever the user creates a table. It is also possible to use CREATE TYPE to define a stand-alone composite type with no associated table. A composite type is simply a list of types with associated field names. A value of a composite type is a row or record of field values. Refer to Section 8.16 for more information.

A range type can hold two values of the same type, which are the lower and upper bounds of the range. Range types are user-created, although a few built-in ones exist. Refer to Section 8.17 for more information.

36.2.3. Domains

A domain is based on a particular underlying type and for many purposes is interchangeable with its underlying type. However, a domain can have constraints that restrict its valid values to a subset of what the underlying type would allow. Domains are created using the SQL command CREATE DOMAIN. Refer to Section 8.18 for more information.

36.2.4. Pseudo-Types

There are a few pseudo-types for special purposes. Pseudo-types cannot appear as columns of tables or components of container types, but they can be used to declare the argument and result types of functions. This provides a mechanism within the type system to identify special classes of functions. Table 8.25 lists the existing pseudo-types.

36.2.5. Polymorphic Types

Five pseudo-types of special interest are anyelement, anyarray, anynonarray, anyenum, and anyrange, which are collectively called polymorphic types. Any function declared using these types is said to be a polymorphic function. A polymorphic function can operate on many different data types, with the specific data type(s) being determined by the data types actually passed to it in a particular call.

Polymorphic arguments and results are tied to each other and are resolved to a specific data type when a query calling a polymorphic function is parsed. Each position (either argument or return value) declared as anyelement is allowed to have any specific actual data type, but in any given call they must all be the same actual type. Each position declared as anyarray can have any array data type, but similarly they must all be the same type. And similarly, positions declared as anyrange must all be the same range type. Furthermore, if there are positions declared anyarray and others declared anyelement, the actual array type in the anyarray positions must be an array whose elements are the same type appearing in the anyelement positions. Similarly, if there are positions declared anyrange and others declared anyelement or anyarray, the actual range type in the anyrange positions must be a range whose subtype is the same type appearing in the anyelement positions and the same as the element type of the anyarray positions. anynonarray is treated exactly the same as anyelement, but adds the additional constraint that the actual type must not be an array type. anyenum is treated exactly the same as anyelement, but adds the additional constraint that the actual type must be an enum type.

Thus, when more than one argument position is declared with a polymorphic type, the net effect is that only certain combinations of actual argument types are allowed. For example, a function declared as equal(anyelement, anyelement) will take any two input values, so long as they are of the same data type.

When the return value of a function is declared as a polymorphic type, there must be at least one argument position that is also polymorphic, and the actual data type supplied as the argument determines the actual result type for that call. For example, if there were not already an array subscripting mechanism, one could define a function that implements subscripting as subscript(anyarray, integer) returns anyelement. This declaration constrains the actual first argument to be an array type, and allows the parser to infer the correct result type from the actual first argument's type. Another example is that a function declared as f(anyarray) returns anyenum will only accept arrays of enum types.

In most cases, the parser can infer the actual data type for a polymorphic result type from arguments that are of a different polymorphic type; for example anyarray can be deduced from anyelement or vice versa. The exception is that a polymorphic result of type anyrange requires an argument of type anyrange; it cannot be deduced from anyarray or anyelement arguments. This is because there could be multiple range types with the same subtype.

Note that anynonarray and anyenum do not represent separate type variables; they are the same type as anyelement, just with an additional constraint. For example, declaring a function as f(anyelement, anyenum) is equivalent to declaring it as f(anyenum, anyenum): both actual arguments have to be the same enum type.

A variadic function (one taking a variable number of arguments, as in Section 36.5.5) can be polymorphic: this is accomplished by declaring its last parameter as VARIADIC anyarray. For purposes of argument matching and determining the actual result type, such a function behaves the same as if you had written the appropriate number of anynonarray parameters.