PostgreSQL 9.3:如何将大写 UUID 插入 table

PostgreSQL 9.3: How to insert upper case UUID into table

我有以下 table,只有 1 列是 id,类型为 UUID

Table: uuidtest

create table uuidtest
(
id uuid
);

插入:

我已经使用 uuid_generate_v4() 生成了 uuid 并且还完成了大写 并将其插入 table.

尝试1:

insert into uuidtest values('{4B36AFC8-5205-49C1-AF16-4DC6F96DB982}');

尝试2:

insert into uuidtest values('4B36AFC8-5205-49C1-AF16-4DC6F96DB982');

现在看结果:

select * from uuidtest;

输出:

id
uuid
-------------------------------------
4b36afc8-5205-49c1-af16-4dc6f96db982
4b36afc8-5205-49c1-af16-4dc6f96db982

我也试过更新:

update uuidtest
set id = upper(id::text)::uuid

但是:输出保持不变:

id
uuid
-------------------------------------
4b36afc8-5205-49c1-af16-4dc6f96db982
4b36afc8-5205-49c1-af16-4dc6f96db982    

首先,您应该注意,在 PostgreSQL 中,UUID 是一个 128 位数字,并且是这样存储的(而不是 36 个字符的字符串!)。我们讨论的是这类数据的输入输出形式。

PostgreSQL manual 说:

The data type uuid stores Universally Unique Identifiers (UUID) as defined by RFC 4122, ISO/IEC 9834-8:2005, and related standards.

...

PostgreSQL also accepts the following alternative forms for input: use of upper-case digits, the standard format surrounded by braces, omitting some or all hyphens, adding a hyphen after any group of four digits.

...

Output is always in the standard form.

RFC 4122 说:

Each field is treated as an integer and has its value printed as a zero-filled hexadecimal digit string with the most significant digit first. The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input.

换句话说,为了遵循标准,该值始终打印为小写。

当然,如果你想用大写字母生成结果,你可以使用类似的东西:

select upper(id::TEXT) from uuidtest;

是的,没错。如果插入到 Postgres 中,它将强制值变为小写。我尝试的有点不同,可能不适用于所有人,即;可能不实用。如果你想在 Postgres 中使用大写的 UUID,那么使用这个 ID:

    String id = java.util.UUID.randomUUID().toString().toUpperCase();

Snipped picture to show IDs in CAPS

此外,如果这没有用,您必须像上面提到的那样尝试: 数据库生成的 UUID 较低:

select uuid_generate_v4();

大写:

select UPPER(uuid_generate_v4()::text);