1

我正在尝试实现他们在这篇文章中谈到的 Instagram 的 UUID: //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 的表还是不同的表?

4

1 回答 1

1

只需创建序列

create sequence engagement.table_id_seq

如果您没有 Instagram 的 64 位 uuid 大小限制,您可以使用更简单的 postgresql 的uuid_generate_v1mc(). postgresqluuid类型为 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;
于 2013-07-07T14:00:38.213 回答