9.4. Строковые функции и операторы
В этом разделе описаны функции и операторы для работы с текстовыми строками. Под строками в данном контексте подразумеваются значения типов character
, character varying
и text
. Если не отмечено обратное, все нижеперечисленные функции работают со всеми этими типами, хотя с типом character
следует учитывать возможные эффекты автоматического дополнения строк пробелами. Некоторые из этих функций также поддерживают битовые строки.
В SQL определены несколько строковых функций, в которых аргументы разделяются не запятыми, а ключевыми словами. Они перечислены в Таблице 9.6. PostgreSQL также предоставляет варианты этих функций с синтаксисом, обычным для функций (см. Таблицу 9.7).
Примечание
До версии 8.3 в PostgreSQL эти функции также прозрачно принимали значения некоторых не строковых типов, неявно приводя эти значения к типу text
. Сейчас такие приведения исключены, так как они часто приводили к неожиданным результатам. Однако оператор конкатенации строк (||
) по-прежнему принимает не только строковые данные, если хотя бы один аргумент имеет строковый тип, как показано в Таблице 9.6. Во всех остальных случаях для повторения предыдущего поведения потребуется добавить явное преобразование в text
.
Таблица 9.6. Строковые функции и операторы языка SQL
Функция | Тип результата | Описание | Пример | Результат |
---|---|---|---|---|
| text | Конкатенация строк | 'Post' || 'greSQL' | PostgreSQL |
или
| text | Конкатенация строк с одним не строковым операндом | 'Value: ' || 42 | Value: 42 |
| int | Число бит в строке | bit_length('jose') | 32 |
или
| int | Число символов в строке | char_length('jose') | 4 |
| text | Переводит символы строки в нижний регистр | lower('TOM') | tom |
| int | Число байт в строке | octet_length('jose') | 4 |
| text | Заменяет подстроку | overlay('Txxxxas' placing 'hom' from 2 for 4) | Thomas |
| int | Положение указанной подстроки | position('om' in 'Thomas') | 3 |
| text | Извлекает подстроку | substring('Thomas' from 2 for 3) | hom |
| text | Извлекает подстроку, соответствующую регулярному выражению в стиле POSIX. Подробно шаблоны описаны в Разделе 9.7. | substring('Thomas' from '...$') | mas |
| text | Извлекает подстроку, соответствующую регулярному выражению в стиле SQL. Подробно шаблоны описаны в Разделе 9.7. | substring('Thomas' from '%#"o_a#"_' for '#') | oma |
| text | Удаляет наибольшую подстроку, содержащую только символы characters (по умолчанию пробелы), с начала (leading ), с конца (trailing ) или с обеих сторон (both , (по умолчанию)) строки string | trim(both 'xyz' from 'yxTomxx') | Tom |
| text | Нестандартный синтаксис trim() | trim(both from 'yxTomxx', 'xyz') | Tom |
| text | Переводит символы строки в верхний регистр | upper('tom') | TOM |
Кроме этого, в PostgreSQL есть и другие функции для работы со строками, перечисленные в Таблице 9.7. Некоторые из них используются в качестве внутренней реализации стандартных строковых функций SQL, приведённых в Таблице 9.6.
Таблица 9.7. Другие строковые функции
Функция | Тип результата | Описание | Пример | Результат |
---|---|---|---|---|
| int | Возвращает ASCII-код первого символа аргумента. Для UTF8 возвращает код символа в Unicode. Для других многобайтных кодировок аргумент должен быть ASCII-символом. | ascii('x') | 120 |
| text | Удаляет наибольшую подстроку, состоящую только из символов characters (по умолчанию пробелов), с начала и с конца строки string | btrim('xyxtrimyyx', 'xyz') | trim |
| text | Возвращает символ с данным кодом. Для UTF8 аргумент воспринимается как код символа Unicode, а для других кодировок он должен указывать на ASCII-символ. Код 0 (NULL) не допускается, так как байты с нулевым кодом в текстовых строках сохранить нельзя. | chr(65) | A |
| text | Соединяет текстовые представления всех аргументов, игнорируя NULL. | concat('abcde', 2, NULL, 22) | abcde222 |
| text | Соединяет все аргументы, кроме первого, через разделитель, игнорируя аргументы NULL. Разделитель указывается в первом аргументе. | concat_ws(',', 'abcde', 2, NULL, 22) | abcde,2,22 |
| bytea | Преобразует строку string из кодировки src_encoding в dest_encoding . Переданная строка должна быть допустимой для исходной кодировки. Преобразования могут быть определены с помощью CREATE CONVERSION . Все встроенные преобразования перечислены в Таблице 9.8. | convert('text_in_utf8', 'UTF8', 'LATIN1') | строка text_in_utf8 , представленная в кодировке Latin-1 (ISO 8859-1) |
| text | Преобразует строку string из кодировки src_encoding в кодировку базы данных. Переданная строка должна быть допустимой для исходной кодировки. | convert_from('text_in_utf8', 'UTF8') | строка text_in_utf8 , представленная в кодировке текущей базы данных |
| bytea | Преобразует строку в кодировку dest_encoding . | convert_to('некоторый текст', 'UTF8') | некоторый текст , представленный в кодировке UTF8 |
| bytea | Получает двоичные данные из текстового представления в string . Значения параметра format те же, что и для функции encode . | decode('MTIzAAE=', 'base64') | \x3132330001 |
| text | Переводит двоичные данные в текстовое представление в одном из форматов: base64 , hex , escape . Формат escape преобразует нулевые байты и байты с 1 в старшем бите в восьмеричные последовательности \nnn и дублирует обратную косую черту. | encode('123\000\001', 'base64') | MTIzAAE= |
| text | Форматирует аргумент в соответствии со строкой формата. Эта функция работает подобно sprintf в языке C. См. Подраздел 9.4.1. | format('Hello %s, %1$s', 'World') | Hello World, World |
| text | Переводит первую букву каждого слова в строке в верхний регистр, а остальные — в нижний. Словами считаются последовательности алфавитно-цифровых символов, разделённые любыми другими символами. | initcap('hi THOMAS') | Hi Thomas |
| text | Возвращает первые n символов в строке. Когда n меньше нуля, возвращаются все символы слева, кроме последних |n |. | left('abcde', 2) | ab |
| int | Число символов в строке string | length('jose') | 4 |
| int | Число символов, которые содержит строка string в заданной кодировке encoding . Переданная строка должна быть допустимой в этой кодировке. | length('jose', 'UTF8') | 4 |
| text | Дополняет строку string слева до длины length символами fill (по умолчанию пробелами). Если длина строки уже больше заданной, она обрезается справа. | lpad('hi', 5, 'xy') | xyxhi |
| text | Удаляет наибольшую подстроку, содержащую только символы characters (по умолчанию пробелы), с начала строки string | ltrim('zzzytest', 'xyz') | test |
| text | Вычисляет MD5-хеш строки string и возвращает результат в 16-ричном виде | md5('abc') | 900150983cd24fb0 d6963f7d28e17f72 |
| name | Возвращает имя текущей клиентской кодировки | pg_client_encoding() | SQL_ASCII |
| text | Переданная строка оформляется для использования в качестве идентификатора в SQL -операторе. При необходимости идентификатор заключается в кавычки (например, если он содержит символы, недопустимые в открытом виде, или буквы в разном регистре). Если переданная строка содержит кавычки, они дублируются. См. также Пример 40.1. | quote_ident('Foo bar') | "Foo bar" |
| text | Переданная строка оформляется для использования в качестве текстовой строки в SQL-операторе. Включённые символы апостроф и обратная косая черта при этом дублируются. Заметьте, что quote_literal возвращает NULL, когда на вход ей передаётся строка NULL; если же нужно получить представление и такого аргумента, лучше использовать quote_nullable . См. также Пример 40.1. | quote_literal(E'O\'Reilly') | 'O''Reilly' |
| text | Переводит данное значение в текстовый вид и заключает в апострофы как текстовую строку. Символы апостроф и обратная косая черта при этом дублируются. | quote_literal(42.5) | '42.5' |
| text | Переданная строка оформляется для использования в качестве текстовой строки в SQL-операторе; при этом для аргумента NULL возвращается строка NULL . Символы апостроф и обратная косая черта дублируются должным образом. См. также Пример 40.1. | quote_nullable(NULL) | NULL |
| text | Переводит данное значение в текстовый вид и заключает в апострофы как текстовую строку, при этом для аргумента NULL возвращается строка NULL . Символы апостроф и обратная косая черта дублируются должным образом. | quote_nullable(42.5) | '42.5' |
| setof text[] | Возвращает все подходящие подстроки, полученные в результате применения регулярного выражения в стиле POSIX к string . Подробности описаны в Подразделе 9.7.3. | regexp_matches('foobarbequebaz', '(bar)(beque)') | {bar,beque} |
| text | Заменяет подстроки, соответствующие заданному регулярному выражению в стиле POSIX. Подробности описаны в Подразделе 9.7.3. | regexp_replace('Thomas', '.[mN]a.', 'M') | ThM |
| text[] | Разделяет содержимое string на элементы, используя в качестве разделителя регулярное выражение POSIX. Подробности описаны в Подразделе 9.7.3. | regexp_split_to_array('hello world', '\s+') | {hello,world} |
| setof text | Разделяет содержимое string на элементы, используя в качестве разделителя регулярное выражение POSIX. Подробности описаны в Подразделе 9.7.3. | regexp_split_to_table('hello world', '\s+') | hello
|
| text | Повторяет содержимое string указанное число (number ) раз | repeat('Pg', 4) | PgPgPgPg |
| text | Заменяет все вхождения в string подстроки from подстрокой to | replace('abcdefabcdef', 'cd', 'XX') | abXXefabXXef |
| text | Возвращает перевёрнутую строку | reverse('abcde') | edcba |
| text | Возвращает последние n символов в строке. Когда n меньше нуля, возвращаются все символы справа, кроме первых |n |. | right('abcde', 2) | de |
| text | Дополняет строку string справа до длины length символами fill (по умолчанию пробелами). Если длина строки уже больше заданной, она обрезается. | rpad('hi', 5, 'xy') | hixyx |
| text | Удаляет наибольшую подстроку, содержащую только символы characters (по умолчанию пробелы), с конца строки string | rtrim('testxxzx', 'xyz') | test |
| text | Разделяет строку string по символу delimiter и возвращает элемент по заданному номеру (считая с 1) | split_part('abc~@~def~@~ghi', '~@~', 2) | def |
| int | Возвращает положение указанной подстроки (подобно position( , но с другим порядком аргументов) | strpos('high', 'ig') | 2 |
| text | Извлекает подстроку (подобно substring( ) | substr('alphabet', 3, 2) | ph |
| text | Преобразует string в ASCII из кодировки encoding (поддерживаются только LATIN1 , LATIN2 , LATIN9 и WIN1250 ) | to_ascii('Karel') | Karel |
| text | Преобразует число number в 16-ричный вид | to_hex(2147483647) | 7fffffff |
| text | Заменяет символы в string , найденные в наборе from , на соответствующие символы в множестве to . Если строка from длиннее to , найденные в исходной строке лишние символы from удаляются. | translate('12345', '143', 'ax') | a2x5 |
Функции concat
, concat_ws
и format
принимают переменное число аргументов, так что им для объединения или форматирования можно передавать значения в виде массива, помеченного ключевым словом VARIADIC
(см. Подраздел 35.4.5). Элементы такого массива обрабатываются, как если бы они были обычными аргументами функции. Если вместо массива в соответствующем аргументе передаётся NULL, функции concat
и concat_ws
возвращают NULL, а format
воспринимает NULL как массив нулевого размера.
См. также агрегатную функцию string_agg
в Разделе 9.20.
Таблица 9.8. Встроенные преобразования
Имя преобразования [a] | Исходная кодировка | Целевая кодировка |
---|---|---|
ascii_to_mic | SQL_ASCII | MULE_INTERNAL |
ascii_to_utf8 | SQL_ASCII | UTF8 |
big5_to_euc_tw | BIG5 | EUC_TW |
big5_to_mic | BIG5 | MULE_INTERNAL |
big5_to_utf8 | BIG5 | UTF8 |
euc_cn_to_mic | EUC_CN | MULE_INTERNAL |
euc_cn_to_utf8 | EUC_CN | UTF8 |
euc_jp_to_mic | EUC_JP | MULE_INTERNAL |
euc_jp_to_sjis | EUC_JP | SJIS |
euc_jp_to_utf8 | EUC_JP | UTF8 |
euc_kr_to_mic | EUC_KR | MULE_INTERNAL |
euc_kr_to_utf8 | EUC_KR | UTF8 |
euc_tw_to_big5 | EUC_TW | BIG5 |
euc_tw_to_mic | EUC_TW | MULE_INTERNAL |
euc_tw_to_utf8 | EUC_TW | UTF8 |
gb18030_to_utf8 | GB18030 | UTF8 |
gbk_to_utf8 | GBK | UTF8 |
iso_8859_10_to_utf8 | LATIN6 | UTF8 |
iso_8859_13_to_utf8 | LATIN7 | UTF8 |
iso_8859_14_to_utf8 | LATIN8 | UTF8 |
iso_8859_15_to_utf8 | LATIN9 | UTF8 |
iso_8859_16_to_utf8 | LATIN10 | UTF8 |
iso_8859_1_to_mic | LATIN1 | MULE_INTERNAL |
iso_8859_1_to_utf8 | LATIN1 | UTF8 |
iso_8859_2_to_mic | LATIN2 | MULE_INTERNAL |
iso_8859_2_to_utf8 | LATIN2 | UTF8 |
iso_8859_2_to_windows_1250 | LATIN2 | WIN1250 |
iso_8859_3_to_mic | LATIN3 | MULE_INTERNAL |
iso_8859_3_to_utf8 | LATIN3 | UTF8 |
iso_8859_4_to_mic | LATIN4 | MULE_INTERNAL |
iso_8859_4_to_utf8 | LATIN4 | UTF8 |
iso_8859_5_to_koi8_r | ISO_8859_5 | KOI8R |
iso_8859_5_to_mic | ISO_8859_5 | MULE_INTERNAL |
iso_8859_5_to_utf8 | ISO_8859_5 | UTF8 |
iso_8859_5_to_windows_1251 | ISO_8859_5 | WIN1251 |
iso_8859_5_to_windows_866 | ISO_8859_5 | WIN866 |
iso_8859_6_to_utf8 | ISO_8859_6 | UTF8 |
iso_8859_7_to_utf8 | ISO_8859_7 | UTF8 |
iso_8859_8_to_utf8 | ISO_8859_8 | UTF8 |
iso_8859_9_to_utf8 | LATIN5 | UTF8 |
johab_to_utf8 | JOHAB | UTF8 |
koi8_r_to_iso_8859_5 | KOI8R | ISO_8859_5 |
koi8_r_to_mic | KOI8R | MULE_INTERNAL |
koi8_r_to_utf8 | KOI8R | UTF8 |
koi8_r_to_windows_1251 | KOI8R | WIN1251 |
koi8_r_to_windows_866 | KOI8R | WIN866 |
koi8_u_to_utf8 | KOI8U | UTF8 |
mic_to_ascii | MULE_INTERNAL | SQL_ASCII |
mic_to_big5 | MULE_INTERNAL | BIG5 |
mic_to_euc_cn | MULE_INTERNAL | EUC_CN |
mic_to_euc_jp | MULE_INTERNAL | EUC_JP |
mic_to_euc_kr | MULE_INTERNAL | EUC_KR |
mic_to_euc_tw | MULE_INTERNAL | EUC_TW |
mic_to_iso_8859_1 | MULE_INTERNAL | LATIN1 |
mic_to_iso_8859_2 | MULE_INTERNAL | LATIN2 |
mic_to_iso_8859_3 | MULE_INTERNAL | LATIN3 |
mic_to_iso_8859_4 | MULE_INTERNAL | LATIN4 |
mic_to_iso_8859_5 | MULE_INTERNAL | ISO_8859_5 |
mic_to_koi8_r | MULE_INTERNAL | KOI8R |
mic_to_sjis | MULE_INTERNAL | SJIS |
mic_to_windows_1250 | MULE_INTERNAL | WIN1250 |
mic_to_windows_1251 | MULE_INTERNAL | WIN1251 |
mic_to_windows_866 | MULE_INTERNAL | WIN866 |
sjis_to_euc_jp | SJIS | EUC_JP |
sjis_to_mic | SJIS | MULE_INTERNAL |
sjis_to_utf8 | SJIS | UTF8 |
windows_1258_to_utf8 | WIN1258 | UTF8 |
uhc_to_utf8 | UHC | UTF8 |
utf8_to_ascii | UTF8 | SQL_ASCII |
utf8_to_big5 | UTF8 | BIG5 |
utf8_to_euc_cn | UTF8 | EUC_CN |
utf8_to_euc_jp | UTF8 | EUC_JP |
utf8_to_euc_kr | UTF8 | EUC_KR |
utf8_to_euc_tw | UTF8 | EUC_TW |
utf8_to_gb18030 | UTF8 | GB18030 |
utf8_to_gbk | UTF8 | GBK |
utf8_to_iso_8859_1 | UTF8 | LATIN1 |
utf8_to_iso_8859_10 | UTF8 | LATIN6 |
utf8_to_iso_8859_13 | UTF8 | LATIN7 |
utf8_to_iso_8859_14 | UTF8 | LATIN8 |
utf8_to_iso_8859_15 | UTF8 | LATIN9 |
utf8_to_iso_8859_16 | UTF8 | LATIN10 |
utf8_to_iso_8859_2 | UTF8 | LATIN2 |
utf8_to_iso_8859_3 | UTF8 | LATIN3 |
utf8_to_iso_8859_4 | UTF8 | LATIN4 |
utf8_to_iso_8859_5 | UTF8 | ISO_8859_5 |
utf8_to_iso_8859_6 | UTF8 | ISO_8859_6 |
utf8_to_iso_8859_7 | UTF8 | ISO_8859_7 |
utf8_to_iso_8859_8 | UTF8 | ISO_8859_8 |
utf8_to_iso_8859_9 | UTF8 | LATIN5 |
utf8_to_johab | UTF8 | JOHAB |
utf8_to_koi8_r | UTF8 | KOI8R |
utf8_to_koi8_u | UTF8 | KOI8U |
utf8_to_sjis | UTF8 | SJIS |
utf8_to_windows_1258 | UTF8 | WIN1258 |
utf8_to_uhc | UTF8 | UHC |
utf8_to_windows_1250 | UTF8 | WIN1250 |
utf8_to_windows_1251 | UTF8 | WIN1251 |
utf8_to_windows_1252 | UTF8 | WIN1252 |
utf8_to_windows_1253 | UTF8 | WIN1253 |
utf8_to_windows_1254 | UTF8 | WIN1254 |
utf8_to_windows_1255 | UTF8 | WIN1255 |
utf8_to_windows_1256 | UTF8 | WIN1256 |
utf8_to_windows_1257 | UTF8 | WIN1257 |
utf8_to_windows_866 | UTF8 | WIN866 |
utf8_to_windows_874 | UTF8 | WIN874 |
windows_1250_to_iso_8859_2 | WIN1250 | LATIN2 |
windows_1250_to_mic | WIN1250 | MULE_INTERNAL |
windows_1250_to_utf8 | WIN1250 | UTF8 |
windows_1251_to_iso_8859_5 | WIN1251 | ISO_8859_5 |
windows_1251_to_koi8_r | WIN1251 | KOI8R |
windows_1251_to_mic | WIN1251 | MULE_INTERNAL |
windows_1251_to_utf8 | WIN1251 | UTF8 |
windows_1251_to_windows_866 | WIN1251 | WIN866 |
windows_1252_to_utf8 | WIN1252 | UTF8 |
windows_1256_to_utf8 | WIN1256 | UTF8 |
windows_866_to_iso_8859_5 | WIN866 | ISO_8859_5 |
windows_866_to_koi8_r | WIN866 | KOI8R |
windows_866_to_mic | WIN866 | MULE_INTERNAL |
windows_866_to_utf8 | WIN866 | UTF8 |
windows_866_to_windows_1251 | WIN866 | WIN |
windows_874_to_utf8 | WIN874 | UTF8 |
euc_jis_2004_to_utf8 | EUC_JIS_2004 | UTF8 |
utf8_to_euc_jis_2004 | UTF8 | EUC_JIS_2004 |
shift_jis_2004_to_utf8 | SHIFT_JIS_2004 | UTF8 |
utf8_to_shift_jis_2004 | UTF8 | SHIFT_JIS_2004 |
euc_jis_2004_to_shift_jis_2004 | EUC_JIS_2004 | SHIFT_JIS_2004 |
shift_jis_2004_to_euc_jis_2004 | SHIFT_JIS_2004 | EUC_JIS_2004 |
[a] Имена преобразований следуют стандартной схеме именования. К официальному названию исходной кодировки, в котором все не алфавитно-цифровые символы заменяются подчёркиваниями, добавляется |
9.4.1. format
Функция format
выдаёт текст, отформатированный в соответствии со строкой формата, подобно функции sprintf
в C.
format
(formatstr
text
[,formatarg
"any"
[, ...] ])
formatstr
— строка, определяющая, как будет форматироваться результат. Обычный текст в строке формата непосредственно копируется в результат, за исключением спецификаторов формата. Спецификаторы формата представляют собой местозаполнители, определяющие, как должны форматироваться и выводиться в результате аргументы функции. Каждый аргумент formatarg
преобразуется в текст по правилам выводам своего типа данных, а затем форматируется и вставляется в результирующую строку согласно спецификаторам формата.
Спецификаторы формата предваряются символом %
и имеют форму
%[позиция
][флаги
][ширина
]тип
Здесь:
позиция
(необязателен)Строка вида
, гдеn
$n
— индекс выводимого аргумента. Индекс, равный 1, выбирает первый аргумент послеformatstr
. Еслипозиция
опускается, по умолчанию используется следующий аргумент по порядку.флаги
(необязателен)Дополнительные параметры, управляющие форматированием данного спецификатора. В настоящее время поддерживается только знак минус (
-
), который выравнивает результата спецификатора по левому краю. Он работает, только если также определенаширина
.ширина
(необязателен)Задаёт минимальное число символов, которое будет занимать результат данного спецификатора. Выводимое значение выравнивается по правой или левой стороне (в зависимости от флага
-
) с дополнением необходимым числом пробелов. Если ширина слишком мала, она просто игнорируется, т. е. результат не усекается. Ширину можно обозначить положительным целым, звёздочкой (*
), тогда ширина будет получена из следующего аргумента функции, или строкой вида*
, тогда ширина будет задаваться вn
$n
-ом аргументе функции.Если ширина передаётся в аргументе функции, этот аргумент выбирается до аргумента, используемого для спецификатора. Если аргумент ширины отрицательный, результат выравнивается по левой стороне (как если бы был указан флаг
-
) в рамках поля длиныabs
(ширина
).тип
(обязателен)Тип спецификатора определяет преобразование соответствующего выводимого значения. Поддерживаются следующие типы:
s
форматирует значение аргумента как простую строку. Значение NULL представляется пустой строкой.I
обрабатывает значение аргумента как SQL-идентификатор, при необходимости заключая его в кавычки. Значение NULL для такого преобразования считается ошибочным (так же, как и дляquote_ident
).L
заключает значение аргумента в апострофы, как строку SQL. Значение NULL выводится буквально, какNULL
, без кавычек (так же, как и сquote_nullable
).
В дополнение к спецификаторам, описанным выше, можно использовать спецпоследовательность %%
, которая просто выведет символ %
.
Несколько примеров простых преобразований формата:
SELECT format('Hello %s', 'World'); Результат:Hello World
SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three'); Результат:Testing one, two, three, %
SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly'); Результат:INSERT INTO "Foo bar" VALUES('O''Reilly')
SELECT format('INSERT INTO %I VALUES(%L)', 'locations', 'C:\Program Files'); Результат:INSERT INTO locations VALUES('C:\Program Files')
Следующие примеры иллюстрируют использование поля ширина
и флага -
:
SELECT format('|%10s|', 'foo'); Результат:| foo|
SELECT format('|%-10s|', 'foo'); Результат:|foo |
SELECT format('|%*s|', 10, 'foo'); Результат:| foo|
SELECT format('|%*s|', -10, 'foo'); Результат:|foo |
SELECT format('|%-*s|', 10, 'foo'); Результат:|foo |
SELECT format('|%-*s|', -10, 'foo'); Результат:|foo |
Эти примеры показывают применение полей позиция
:
SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three'); Результат:Testing three, two, one
SELECT format('|%*2$s|', 'foo', 10, 'bar'); Результат:| bar|
SELECT format('|%1$*2$s|', 'foo', 10, 'bar'); Результат:| foo|
В отличие от стандартной функции C sprintf
, функция format
в PostgreSQL позволяет комбинировать в одной строке спецификаторы с полями позиция
и без них. Спецификатор формата без поля позиция
всегда использует следующий аргумент после последнего выбранного. Кроме того, функция format
не требует, чтобы в строке формата использовались все аргументы функции. Пример этого поведения:
SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
Результат: Testing three, two, three
Спецификаторы формата %I
и %L
особенно полезны для безопасного составления динамических операторов SQL. См. Пример 40.1.
33.10. Functions Associated with the COPY
Command
The COPY
command in Postgres Pro has options to read from or write to the network connection used by libpq. The functions described in this section allow applications to take advantage of this capability by supplying or consuming copied data.
The overall process is that the application first issues the SQL COPY
command via PQexec
or one of the equivalent functions. The response to this (if there is no error in the command) will be a PGresult
object bearing a status code of PGRES_COPY_OUT
or PGRES_COPY_IN
(depending on the specified copy direction). The application should then use the functions of this section to receive or transmit data rows. When the data transfer is complete, another PGresult
object is returned to indicate success or failure of the transfer. Its status will be PGRES_COMMAND_OK
for success or PGRES_FATAL_ERROR
if some problem was encountered. At this point further SQL commands can be issued via PQexec
. (It is not possible to execute other SQL commands using the same connection while the COPY
operation is in progress.)
If a COPY
command is issued via PQexec
in a string that could contain additional commands, the application must continue fetching results via PQgetResult
after completing the COPY
sequence. Only when PQgetResult
returns NULL
is it certain that the PQexec
command string is done and it is safe to issue more commands.
The functions of this section should be executed only after obtaining a result status of PGRES_COPY_OUT
or PGRES_COPY_IN
from PQexec
or PQgetResult
.
A PGresult
object bearing one of these status values carries some additional data about the COPY
operation that is starting. This additional data is available using functions that are also used in connection with query results:
PQnfields
Returns the number of columns (fields) to be copied.
PQbinaryTuples
0 indicates the overall copy format is textual (rows separated by newlines, columns separated by separator characters, etc). 1 indicates the overall copy format is binary. See COPY for more information.
PQfformat
Returns the format code (0 for text, 1 for binary) associated with each column of the copy operation. The per-column format codes will always be zero when the overall copy format is textual, but the binary format can support both text and binary columns. (However, as of the current implementation of
COPY
, only binary columns appear in a binary copy; so the per-column formats always match the overall format at present.)
33.10.1. Functions for Sending COPY
Data
These functions are used to send data during COPY FROM STDIN
. They will fail if called when the connection is not in COPY_IN
state.
PQputCopyData
Sends data to the server during
COPY_IN
state.int PQputCopyData(PGconn *conn, const char *buffer, int nbytes);
Transmits the
COPY
data in the specifiedbuffer
, of lengthnbytes
, to the server. The result is 1 if the data was queued, zero if it was not queued because of full buffers (this will only happen in nonblocking mode), or -1 if an error occurred. (UsePQerrorMessage
to retrieve details if the return value is -1. If the value is zero, wait for write-ready and try again.)The application can divide the
COPY
data stream into buffer loads of any convenient size. Buffer-load boundaries have no semantic significance when sending. The contents of the data stream must match the data format expected by theCOPY
command; see COPY for details.PQputCopyEnd
Sends end-of-data indication to the server during
COPY_IN
state.int PQputCopyEnd(PGconn *conn, const char *errormsg);
Ends the
COPY_IN
operation successfully iferrormsg
isNULL
. Iferrormsg
is notNULL
then theCOPY
is forced to fail, with the string pointed to byerrormsg
used as the error message. (One should not assume that this exact error message will come back from the server, however, as the server might have already failed theCOPY
for its own reasons.)The result is 1 if the termination message was sent; or in nonblocking mode, this may only indicate that the termination message was successfully queued. (In nonblocking mode, to be certain that the data has been sent, you should next wait for write-ready and call
PQflush
, repeating until it returns zero.) Zero indicates that the function could not queue the termination message because of full buffers; this will only happen in nonblocking mode. (In this case, wait for write-ready and try thePQputCopyEnd
call again.) If a hard error occurs, -1 is returned; you can usePQerrorMessage
to retrieve details.After successfully calling
PQputCopyEnd
, callPQgetResult
to obtain the final result status of theCOPY
command. One can wait for this result to be available in the usual way. Then return to normal operation.
33.10.2. Functions for Receiving COPY
Data
These functions are used to receive data during COPY TO STDOUT
. They will fail if called when the connection is not in COPY_OUT
state.
PQgetCopyData
Receives data from the server during
COPY_OUT
state.int PQgetCopyData(PGconn *conn, char **buffer, int async);
Attempts to obtain another row of data from the server during a
COPY
. Data is always returned one data row at a time; if only a partial row is available, it is not returned. Successful return of a data row involves allocating a chunk of memory to hold the data. Thebuffer
parameter must be non-NULL
.*buffer
is set to point to the allocated memory, or toNULL
in cases where no buffer is returned. A non-NULL
result buffer should be freed usingPQfreemem
when no longer needed.When a row is successfully returned, the return value is the number of data bytes in the row (this will always be greater than zero). The returned string is always null-terminated, though this is probably only useful for textual
COPY
. A result of zero indicates that theCOPY
is still in progress, but no row is yet available (this is only possible whenasync
is true). A result of -1 indicates that theCOPY
is done. A result of -2 indicates that an error occurred (consultPQerrorMessage
for the reason).When
async
is true (not zero),PQgetCopyData
will not block waiting for input; it will return zero if theCOPY
is still in progress but no complete row is available. (In this case wait for read-ready and then callPQconsumeInput
before callingPQgetCopyData
again.) Whenasync
is false (zero),PQgetCopyData
will block until data is available or the operation completes.After
PQgetCopyData
returns -1, callPQgetResult
to obtain the final result status of theCOPY
command. One can wait for this result to be available in the usual way. Then return to normal operation.
33.10.3. Obsolete Functions for COPY
These functions represent older methods of handling COPY
. Although they still work, they are deprecated due to poor error handling, inconvenient methods of detecting end-of-data, and lack of support for binary or nonblocking transfers.
PQgetline
Reads a newline-terminated line of characters (transmitted by the server) into a buffer string of size
length
.int PQgetline(PGconn *conn, char *buffer, int length);
This function copies up to
length
-1 characters into the buffer and converts the terminating newline into a zero byte.PQgetline
returnsEOF
at the end of input, 0 if the entire line has been read, and 1 if the buffer is full but the terminating newline has not yet been read.Note that the application must check to see if a new line consists of the two characters
\.
, which indicates that the server has finished sending the results of theCOPY
command. If the application might receive lines that are more thanlength
-1 characters long, care is needed to be sure it recognizes the\.
line correctly (and does not, for example, mistake the end of a long data line for a terminator line).PQgetlineAsync
Reads a row of
COPY
data (transmitted by the server) into a buffer without blocking.int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize);
This function is similar to
PQgetline
, but it can be used by applications that must readCOPY
data asynchronously, that is, without blocking. Having issued theCOPY
command and gotten aPGRES_COPY_OUT
response, the application should callPQconsumeInput
andPQgetlineAsync
until the end-of-data signal is detected.Unlike
PQgetline
, this function takes responsibility for detecting end-of-data.On each call,
PQgetlineAsync
will return data if a complete data row is available in libpq's input buffer. Otherwise, no data is returned until the rest of the row arrives. The function returns -1 if the end-of-copy-data marker has been recognized, or 0 if no data is available, or a positive number giving the number of bytes of data returned. If -1 is returned, the caller must next callPQendcopy
, and then return to normal processing.The data returned will not extend beyond a data-row boundary. If possible a whole row will be returned at one time. But if the buffer offered by the caller is too small to hold a row sent by the server, then a partial data row will be returned. With textual data this can be detected by testing whether the last returned byte is
\n
or not. (In a binaryCOPY
, actual parsing of theCOPY
data format will be needed to make the equivalent determination.) The returned string is not null-terminated. (If you want to add a terminating null, be sure to pass abufsize
one smaller than the room actually available.)PQputline
Sends a null-terminated string to the server. Returns 0 if OK and
EOF
if unable to send the string.int PQputline(PGconn *conn, const char *string);
The
COPY
data stream sent by a series of calls toPQputline
has the same format as that returned byPQgetlineAsync
, except that applications are not obliged to send exactly one data row perPQputline
call; it is okay to send a partial line or multiple lines per call.Note
Before Postgres Pro protocol 3.0, it was necessary for the application to explicitly send the two characters
\.
as a final line to indicate to the server that it had finished sendingCOPY
data. While this still works, it is deprecated and the special meaning of\.
can be expected to be removed in a future release. It is sufficient to callPQendcopy
after having sent the actual data.PQputnbytes
Sends a non-null-terminated string to the server. Returns 0 if OK and
EOF
if unable to send the string.int PQputnbytes(PGconn *conn, const char *buffer, int nbytes);
This is exactly like
PQputline
, except that the data buffer need not be null-terminated since the number of bytes to send is specified directly. Use this procedure when sending binary data.PQendcopy
Synchronizes with the server.
int PQendcopy(PGconn *conn);
This function waits until the server has finished the copying. It should either be issued when the last string has been sent to the server using
PQputline
or when the last string has been received from the server usingPQgetline
. It must be issued or the server will get “out of sync” with the client. Upon return from this function, the server is ready to receive the next SQL command. The return value is 0 on successful completion, nonzero otherwise. (UsePQerrorMessage
to retrieve details if the return value is nonzero.)When using
PQgetResult
, the application should respond to aPGRES_COPY_OUT
result by executingPQgetline
repeatedly, followed byPQendcopy
after the terminator line is seen. It should then return to thePQgetResult
loop untilPQgetResult
returns a null pointer. Similarly aPGRES_COPY_IN
result is processed by a series ofPQputline
calls followed byPQendcopy
, then return to thePQgetResult
loop. This arrangement will ensure that aCOPY
command embedded in a series of SQL commands will be executed correctly.Older applications are likely to submit a
COPY
viaPQexec
and assume that the transaction is done afterPQendcopy
. This will work correctly only if theCOPY
is the only SQL command in the command string.