从文档看到如下例子
此外,还可以将整数值转换为 bytea 类型,反之亦然。将整数转换为 bytea 会根据整数类型的宽度生成 2、4 或 8 个字节。结果是整数的二补数表示,最高有效字节在前。一些示例:
1234::smallint::bytea \x04d2
cast(1234 as bytea) \x000004d2
cast(-1234 as bytea) \xfffffb2e
'\x8000'::bytea::smallint -32768
'\x8000'::bytea::integer 32768
测试了一下,确实如此
psql (18.0 (Debian 18.0-1.pgdg13+3))
Type "help" for help.
postgres=# select 1234::bytea;
bytea
------------
\x000004d2
(1 row)
postgres=# select 1234::smallint::bytea;
bytea
--------
\x04d2
(1 row)
作为比较,17.7版不支持以上操作, 只支持把字符串转换为bytea 类型
postgres=# select 1234::smallint::bytea;
ERROR: cannot cast type smallint to bytea
LINE 1: select 1234::smallint::bytea;
^
postgres=# select 1234::bytea;
ERROR: cannot cast type integer to bytea
LINE 1: select 1234::bytea;
^
postgres=# select '1234'::bytea;
bytea
------------
\x31323334
(1 row)
postgres=# select 1234::smallint::text::bytea;
bytea
------------
\x31323334
(1 row)