如何生成没有破折号的uuid [英] How to generate uuids without dashes
问题描述
我正在创建一个具有以下表定义的表
I am creating a table with the following table definition
CREATE TABLE auth(
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
role VARCHAR(64)
);
生成的 uuid 格式为 a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11
我知道 postgres 也接受不带连字符的 uuid.我们如何指定自动生成的 uuid 中没有连字符?
The uuids generated are in the form a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11
I know postgres also accepts uuids without hyphens. How can we specify the auto-generated uuids do not have hyphens in it?
推荐答案
这里有一个可行的解决方案,可以实现与您要求的接近的目标:
Here is a working solution to achieve something close to what you ask:
CREATE TABLE foo (
ts TIMESTAMP WITH TIME ZONE,
uuid VARCHAR DEFAULT REPLACE(uuid_generate_v4()::text, '-', '' )
);
INSERT INTO foo ( ts ) VALUES ( now() );
BUT (and it is a big but) 在这里我们将 uuid
转换为 string
这意味着索引本身会更多比数字或真正的 uuid
昂贵.
BUT (and it is a big but) here we convert uuid
to a string
that means that the index itself will be much more expensive than a number or a real uuid
.
在这篇文章中你可以找到一个很好的解释:
https://tomharrisonjr.com/uuid-or-guid-as-primary-keys-be-careful-7b2aa3dcb439
In this article you can find a good explanation:
https://tomharrisonjr.com/uuid-or-guid-as-primary-keys-be-careful-7b2aa3dcb439
据我所知,即使您尝试删除它们,Postgres 的 uuid
也会使用连字符:
As far as I know, Postgres' uuid
uses hyphens even if you try to remove them:
CREATE TABLE foo (
ts TIMESTAMP WITH TIME ZONE,
queue UUID DEFAULT REPLACE(uuid_generate_v4()::text, '-', '' )::uuid,
);
INSERT INTO foo ( ts ) VALUES ( now() );
上面的示例在 Postgres 9.6 中运行良好,但是当我们转换回 uuid
时,连字符被添加回来.
The example above works just fine in Postgres 9.6, but when we cast back to uuid
hyphens are added back.
这篇关于如何生成没有破折号的uuid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!