我正在尝试实现他们在这篇文章中谈到的Instagram的UUID:http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
我的实现看起来像这样:
CREATE OR REPLACE FUNCTION engagement.next_id(OUT result bigint) AS $$
DECLARE
our_epoch bigint := 1314220021721;
seq_id bigint;
now_millis bigint;
shard_id int := 5;
BEGIN
SELECT nextval('engagement.table_id_seq') %% 1024 INTO seq_id;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - our_epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;
但我一直收到这个错误:
Warning: pg_execute(): Query failed: ERROR: relation "engagement.table_id_seq" does not exist LINE 1: SELECT nextval('engagement.table_id_seq') %% 1024 ^ QUERY: SELECT nextval('engagement.table_id_seq') %% 1024 CONTEXT: PL/pgSQL function next_id() line 8
我实际上是想创建一个名为table_id_seq的表或者不同的表吗?
只需创建序列
create sequence engagement.table_id_seq
如果你没有Instagram的64位uuid大小限制,你可以使用更简单的postgresql的uuid_generate_v1mc()
。 postgresql uuid
类型是128位长。
create table t (id serial, uid uuid);
insert into t (uid)
select uuid_generate_v1mc()
from generate_series(1, 100000);
它可以按创建时间排序:
select *
from (
select
*,
row_number() over(order by uid) rn
from t
order by id
) s
where id != rn;