数据库

pg_hashids: 短UID生成


pg_hashids 提供了一种安全的方式,可以从数字生成简短、唯一且非连续的ID。这些哈希值旨在成为小巧易记的标识符,可选择性地通过密码、字母表和盐值来混淆数据。例如,您可能希望隐藏用户ID、订单号或跟踪代码等数据,转而使用pg_hashid生成的唯一标识符。

启用扩展

  1. 进入仪表盘的数据库页面
  2. 点击侧边栏中的扩展
  3. 搜索"pg_hashids"并启用该扩展

使用方法

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

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

要将 short_id 反向解码回 id,可以使用对应的 id_decode 函数。

相关资源