| Документация по PostgreSQL 9.4.1 | |||
|---|---|---|---|
| Пред. | Уровень выше | Глава 9. Функции и операторы | След. |
9.5. Функции и операторы двоичных строк
В этом разделе описываются функции и операторы для работы с данными типа bytea.
В SQL определены несколько строковых функций, в которых аргументы разделяются не запятыми, а ключевыми словами. Подробнее это описано в Таблице 9-9. PostgreSQL также предоставляет варианты этих функций с синтаксисом, обычным для функций (см. Таблицу 9-10).
Замечание: В примерах, приведённых на этой странице, подразумевается, что параметр сервера bytea_output равен escape (выбран традиционный формат PostgreSQL).
Таблица 9-9. SQL-функции и операторы для работы с двоичными строками
| Функция | Тип результата | Описание | Пример | Результат |
|---|---|---|---|---|
| string || string | bytea | Конкатенация строк | E'\\\\Post'::bytea || E'\\047gres\\000'::bytea | \\Post'gres\000 |
octet_length(string) | int | Число байт в двоичной строке | octet_length(E'jo\\000se'::bytea) | 5 |
overlay(string placing string from int [for int]) | bytea | Заменяет подстроку | overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3) | T\\002\\003mas |
position(substring in string) | int | Положение указанной подстроки | position(E'\\000om'::bytea in E'Th\\000omas'::bytea) | 3 |
substring(string [from int] [for int]) | bytea | Извлекает подстроку | substring(E'Th\\000omas'::bytea from 2 for 3) | h\000o |
trim([both] bytes from string) | bytea | Удаляет наибольшую подстроку, содержащую только байты bytes, с начала и с конца строки string | trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) | Tom |
В PostgreSQL есть и другие функции для работы с двоичными строками, перечисленные в Таблице 9-10. Некоторые из них используются в качестве внутренней реализации стандартных функций SQL, приведённых в Таблице 9-9.
Таблица 9-10. Другие функции для работы с двоичными строками
| Функция | Тип результата | Описание | Пример | Результат |
|---|---|---|---|---|
btrim(string bytea, bytes bytea) | bytea | Удаляет наибольшую подстроку, состоящую только из байт bytes, с начала и с конца строки string | btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea) | trim |
decode(string text, format text) | bytea | Получает двоичные данные из текстового представления в string. Значения параметра format те же, что и для функции encode. | decode(E'123\\000456', 'escape') | 123\000456 |
encode(data bytea, format text) | text | Переводит двоичные данные в текстовое представление в одном из форматов: base64, hex, escape. Формат escape преобразует нулевые байты и байты с 1 в старшем бите в восьмеричные последовательности \nnn и дублирует обратную косую черту. | encode(E'123\\000456'::bytea, 'escape') | 123\000456 |
get_bit(string, offset) | int | Извлекает бит из строки | get_bit(E'Th\\000omas'::bytea, 45) | 1 |
get_byte(string, offset) | int | Извлекает байт из строки | get_byte(E'Th\\000omas'::bytea, 4) | 109 |
length(string) | int | Длина двоичной строки | length(E'jo\\000se'::bytea) | 5 |
md5(string) | text | Вычисляет MD5-хеш строки string и возвращает результат в 16-ричном виде | md5(E'Th\\000omas'::bytea) | 8ab2d3c9689aaf18 b4958c334c82d8b1 |
set_bit(string, offset, newvalue) | bytea | Устанавливает значение бита в строке | set_bit(E'Th\\000omas'::bytea, 45, 0) | Th\000omAs |
set_byte(string, offset, newvalue) | bytea | Устанавливает значение байта в строке | set_byte(E'Th\\000omas'::bytea, 4, 64) | Th\000o@as |
Для функций get_byte и set_byte байты нумеруется с 0. Функции get_bit и set_bit нумеруют биты справа налево; например, бит 0 будет меньшим значащим битом первого байта, а бит 15 — большим значащим битом второго байта.
См. также агрегатную функцию string_agg в Разделе 9.20 и функции для работы с большими объектами в Разделе 32.4.
| Пред. | Начало | След. |
| Строковые функции и операторы | Уровень выше | Функции и операторы для работы с битовыми строками |
| PostgreSQL 9.4.1 Documentation | |||
|---|---|---|---|
| Prev | Up | Chapter 9. Functions and Operators | Next |
9.5. Binary String Functions and Operators
This section describes functions and operators for examining and manipulating values of type bytea.
SQL defines some string functions that use key words, rather than commas, to separate arguments. Details are in Table 9-9. PostgreSQL also provides versions of these functions that use the regular function invocation syntax (see Table 9-10).
Note: The sample results shown on this page assume that the server parameter bytea_output is set to escape (the traditional PostgreSQL format).
Table 9-9. SQL Binary String Functions and Operators
| Function | Return Type | Description | Example | Result |
|---|---|---|---|---|
| string || string | bytea | String concatenation | E'\\\\Post'::bytea || E'\\047gres\\000'::bytea | \\Post'gres\000 |
octet_length(string) | int | Number of bytes in binary string | octet_length(E'jo\\000se'::bytea) | 5 |
overlay(string placing string from int [for int]) | bytea | Replace substring | overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3) | T\\002\\003mas |
position(substring in string) | int | Location of specified substring | position(E'\\000om'::bytea in E'Th\\000omas'::bytea) | 3 |
substring(string [from int] [for int]) | bytea | Extract substring | substring(E'Th\\000omas'::bytea from 2 for 3) | h\000o |
trim([both] bytes from string) | bytea | Remove the longest string containing only the bytes in bytes from the start and end of string | trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) | Tom |
Additional binary string manipulation functions are available and are listed in Table 9-10. Some of them are used internally to implement the SQL-standard string functions listed in Table 9-9.
Table 9-10. Other Binary String Functions
| Function | Return Type | Description | Example | Result |
|---|---|---|---|---|
btrim(string bytea, bytes bytea) | bytea | Remove the longest string consisting only of bytes in bytes from the start and end of string | btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea) | trim |
decode(string text, format text) | bytea | Decode binary data from textual representation in string. Options for format are same as in encode. | decode(E'123\\000456', 'escape') | 123\000456 |
encode(data bytea, format text) | text | Encode binary data into a textual representation. Supported formats are: base64, hex, escape. escape converts zero bytes and high-bit-set bytes to octal sequences (\nnn) and doubles backslashes. | encode(E'123\\000456'::bytea, 'escape') | 123\000456 |
get_bit(string, offset) | int | Extract bit from string | get_bit(E'Th\\000omas'::bytea, 45) | 1 |
get_byte(string, offset) | int | Extract byte from string | get_byte(E'Th\\000omas'::bytea, 4) | 109 |
length(string) | int | Length of binary string | length(E'jo\\000se'::bytea) | 5 |
md5(string) | text | Calculates the MD5 hash of string, returning the result in hexadecimal | md5(E'Th\\000omas'::bytea) | 8ab2d3c9689aaf18 b4958c334c82d8b1 |
set_bit(string, offset, newvalue) | bytea | Set bit in string | set_bit(E'Th\\000omas'::bytea, 45, 0) | Th\000omAs |
set_byte(string, offset, newvalue) | bytea | Set byte in string | set_byte(E'Th\\000omas'::bytea, 4, 64) | Th\000o@as |
get_byte and set_byte number the first byte of a binary string as byte 0. get_bit and set_bit number bits from the right within each byte; for example bit 0 is the least significant bit of the first byte, and bit 15 is the most significant bit of the second byte.
See also the aggregate function string_agg in Section 9.20 and the large object functions in Section 32.4.