postgresql:md5 消息摘要的数据类型? [英] postgresql: data type for md5 message digest?
问题描述
我想使用某个字符串的 MD5 消息摘要作为表的主键.我应该为这样的字段使用什么数据类型?我应该为该字段编写哪些 select
和 insert
语句?
I want to use the MD5 message digest of some string as the primary key of a table. What datatype should I use for such a field? What select
and insert
statements should I write for the field?
推荐答案
作为 bytea
的 md5 哈希将仅使用 16 个字节而不是 32 个字节用于六进制表示:
The md5 hash as bytea
will use only 16 bytes in instead of 32 for the hexa representation:
create table t (d bytea);
insert into t (d) values
(digest('my_string', 'md5')),
(decode(md5('my_string'), 'hex'));
以上两种形式都可以使用,但要使用更简单的 digest
功能,必须以超级用户身份安装 pgcrypto
扩展:
Both forms above will work but to use the simpler digest
function it is necessary to install the pgcrypto
extension as superuser:
create extension pgcrypto;
使用上面的digest
函数或者decode
和md5
的组合来搜索某个字符串:
Use the digest
function or the combination of decode
and md5
as above to search for a certain string:
select
octet_length(d) ba_length,
pg_column_size(d) ba_column,
encode(d, 'hex') hex_representation,
octet_length(encode(d, 'hex')) h_length,
pg_column_size(encode(d, 'hex')) h_column
from t
where d = digest('my_string', 'md5')
;
ba_length | ba_column | hex_representation | h_length | h_column
-----------+-----------+----------------------------------+----------+----------
16 | 17 | 3d212b21fad7bed63c1fb560c6a5c5d0 | 32 | 36
16 | 17 | 3d212b21fad7bed63c1fb560c6a5c5d0 | 32 | 36
pg_column_size
值是存储大小.与六进制表示相比,bytea
不到一半.
The pg_column_size
value is the storage size. It is less than half for the bytea
compared to the hexa representation.
这篇关于postgresql:md5 消息摘要的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!