本节描述用于检查和操作 bytea 类型值的函数和操作符。
SQL定义了一些二进制串函数,它们使用关键字而不是逗号来分隔参数。详情见表 9.8。PostgreSQL也提供了这些函数使用正常函数调用语法的版本(见表 9.9)。
表 9.8. SQL二进制串函数和操作符
| 函数 | 返回类型 | 描述 | 示例 | 结果 |
|---|
string ||
string | bytea | 字符串串接 | E'\\\\Post'::bytea || E'\\047gres\\000'::bytea | \\Post'gres\000 |
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 |
octet_length(string) | int | 二进制串中的字节数 | octet_length(E'jo\\000se'::bytea) | 5 |
position(substring in string) | int | 指定子串的位置 | position(E'\\000om'::bytea in E'Th\\000omas'::bytea) | 3 |
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 |
substring(string [from int] [for int]) | bytea | 提取子串
| substring(E'Th\\000omas'::bytea from 2 for 3) | h\000o |
trim([both]
bytes from
string)
| bytea | 移除string开始端和结束端仅含bytes中的字节(默认为空格)组成的最长字符串
| trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) | Tom |
还有一些二进制串处理函数可以使用,在表 9.9列出。其中有一些是在内部使用,用于实现表 9.8列出的 SQL 标准串函数。
表 9.9. 其他二进制串函数
| 函数 | 返回类型 | 描述 | 示例 | 结果 |
|---|
btrim(string
bytea, bytes bytea) | bytea | 移除string开始端和结束端仅由bytes中的字节组成的最长字符串
| 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 | 把二进制数据编码为文本表示。支持的
formats are: base64, hex, escape.
escape将零字节和高位置位的字节转换为八进制序列(\nnn),并将反斜线双写。
| encode(E'123\\000456'::bytea, 'escape') | 123\000456 |
length(string) | int | 二进制串的长度
| length(E'jo\\000se'::bytea) | 5 |
md5(string) | text | 计算string的 MD5 哈希,以十六进制返回结果
| md5(E'Th\\000omas'::bytea) | 8ab2d3c9689aaf18 b4958c334c82d8b1 |