从 PostgreSQL 中的 v1 UUID 投射或提取时间戳 [英] Cast or extract timestamp from v1 UUID in PostgreSQL
本文介绍了从 PostgreSQL 中的 v1 UUID 投射或提取时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 第 1 版 UUID,天真地希望这能奏效:
I'm trying to extract the timestamp from a Version 1 UUID, naively wished this worked:
SELECT '3efe0a20-f1b3-11e3-bb44-14109fec739e'::uuid::timestamp;
这里是一个简单的例子,展示了如何在 Go 中提取时间,但我希望 PostgreSQL 有内置的东西,而不是创建一次性的 PL/pgSql 函数:
http://play.golang.org/p/XRCooLgfaG
Here is a quick example showing how to extract the time in Go, but I'm hoping PostgreSQL has something built-in rather than creating a one-off PL/pgSql function:
http://play.golang.org/p/XRCooLgfaG
推荐答案
我已经用我的数据库中的 uuid 测试了这个,它似乎工作得很好,即使没有 unsigned bigints
I've tested this with uuid's from my database and it seems to work very well, even without the unsigned bigints
CREATE FUNCTION uuid_timestamp(id uuid) RETURNS timestamptz AS $$
select TIMESTAMP WITH TIME ZONE 'epoch' +
(((('x' || lpad(split_part(id::text, '-', 1), 16, '0'))::bit(64)::bigint) +
(('x' || lpad(split_part(id::text, '-', 2), 16, '0'))::bit(64)::bigint << 32) +
((('x' || lpad(split_part(id::text, '-', 3), 16, '0'))::bit(64)::bigint&4095) << 48) - 122192928000000000) / 10000000 ) * INTERVAL '1 second';
$$ LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
我在 2099 年未来创建的 V1 uuid!
a V1 uuid I created in the 2099 future!
select uuid_timestamp('6d248400-65b7-1243-a57a-14109fec739e');
uuid_timestamp
------------------------
2099-08-01 11:30:00-07
(1 row)
这篇关于从 PostgreSQL 中的 v1 UUID 投射或提取时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文