Skip to content
Database

pg_hashids:短 UID

pg_hashids 提供了一种安全的方式,从数字生成短小、独特且非连续的 ID。这些哈希旨在成为小巧、易记的标识符,可以用来(可选地)通过密码、字母表和盐来混淆数据。例如,你可能想隐藏像用户 ID、订单号或追踪码这样的数据,而使用 pg_hashid 的独特标识符。

启用扩展 #

🌐 Enable the extension

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

用法 #

🌐 Usage

假设我们有一个存储订单信息的表,我们想给客户一个唯一的标识符,而不暴露连续的 id 列。为此,我们可以使用 pg_hashidid_encode 函数。

🌐 Suppose we have a table that stores order information, and we want to give customers a unique identifier without exposing the sequential id column. To do this, we can use pg_hashid's id_encode function.

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

🌐 To reverse the short_id back into an id, there is an equivalent function named id_decode.

资源 #

🌐 Resources