数据库

pg_hashids:简短的 UID


pg_hashids 提供了一种安全的方式来从数字生成短小、唯一且非连续的 ID。这些哈希旨在成为小型、易于记忆的标识符,可用于模糊处理数据(可选),并使用密码、字母表和盐。例如,您可能希望隐藏诸如用户 ID、订单号或跟踪代码等数据,而选择使用 pg_hashid 的唯一标识符。

启用扩展#

  1. 转到仪表板中的 数据库 页面。
  2. 在侧边栏中单击 扩展
  3. 搜索 "pg_hashids" 并启用该扩展。

用法#

假设我们有一个存储订单信息的表,并且我们希望向客户提供一个唯一的标识符,而无需暴露顺序 id 列。为此,我们可以使用 pg_hashidid_encode 函数。

1
create table orders (
2
id serial primary key,
3
description text,
4
price_cents bigint
5
);
6
7
insert into orders (description, price_cents)
8
values ('a book', 9095);
9
10
select
11
id,
12
id_encode(id) as short_id,
13
description,
14
price_cents
15
from
16
orders;
17
18
id | short_id | description | price_cents
19
----+----------+-------------+-------------
20
1 | jR | a book | 9095
21
(1 row)

要将 short_id 转换回 id,有一个名为 id_decode 的等效函数。

资源#