实现说明
一个文件里不止一条语句:SELECT / INSERT / CREATE,attachments 都在涉及之列。
真正干活的子句:ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。
常见问题
这个脚本里出现了哪些表?
引用的是 attachments。
核心语句
SELECT id,
encode(payload, 'hex') AS hex_text,
encode(payload, 'base64') AS base64_text,
length(payload) AS byte_length
FROM attachments
ORDER BY id;
INSERT INTO attachments (id, payload)
VALUES
(1, decode('48656c6c6f', 'hex')),
(2, decode('4465764578', 'hex')),
(3, convert_to('café', 'UTF8'));
SELECT encode(decode(encode(payload, 'base64'), 'base64'), 'hex')
= encode(payload, 'hex') AS round_trip
FROM attachments;
代码示例
CREATE TABLE attachments (
id int PRIMARY KEY,
payload bytea NOT NULL
);
INSERT INTO attachments (id, payload)
VALUES
(1, decode('48656c6c6f', 'hex')),
(2, decode('4465764578', 'hex')),
(3, convert_to('café', 'UTF8'));
SELECT id,
encode(payload, 'hex') AS hex_text,
encode(payload, 'base64') AS base64_text,
length(payload) AS byte_length
FROM attachments
ORDER BY id;
-- decode reverses encode for both formats.
SELECT encode(decode(encode(payload, 'base64'), 'base64'), 'hex')
= encode(payload, 'hex') AS round_trip
FROM attachments;
-- escape keeps printable ASCII and escapes control bytes.
SELECT encode(
convert_to('line 1' || chr(10) || 'line 2', 'UTF8'),
'escape'
) AS escaped;