PostgreSQL中使用UUID UUID(Universal Unique Identifier)或者 GUID(Globally Unique Identifier)是一个 128 比特的数字,可以用于唯一标识每个网络对象或资源。由于它的生成机制,一个 UUID 可以保证几乎不会与其他 UUID 重复,因此常常用于生成数据库中的主键值。 1.PostgreSQL 中的 UUID 1.pgcrypto 模块提供的 uuid PostgreSQL 提供了一个用于加/解密的扩展模块 pgcrypto,其中的 gen_random_uuid() 函数可以用于返回一个 version 4 的随机 UUID。 2.uuid-ossp 模块提供的 uuid uuid-ossp模块提供函数使用几种标准算法之一产生通用唯一标识符(UUID)。还提供产生某些特殊 UUID 常量的函数。 2.安装扩展模块 1.将当前目录转移到 PostgreSQL 源代码目录下的 contrib;如: cd /usr/local/postgresql-14.1/contrib 2.执行如下命令来安装扩展模块 make make install 如果要安装 uuid-ossp 模块,需要在执行安装扩展模块之前,执行 configure 并添加 --with-uuid=xxx,xxx取值为: --with-uuid=bsd 可使用 BSD 的函数 --with-uuid=e2fs 会使用e2fsprogs的libuuid --with-uuid=ossp 则会使用OSSP UUID库 然后再执行安装扩展模块的命令。 3.检查是否安装,在 PostgreSQL 的安装目录下的 /share/extension 目录下,查看是否有模块相关的文件。如: cd /usr/local/pgsql/share/extension ls -l pgcrypto* -rw-r--r-- 1 postgres postgres 307 Apr 29 20:53 pgcrypto--1.0--1.1.sql -rw-r--r-- 1 postgres postgres 483 Apr 29 20:53 pgcrypto--1.1--1.2.sql -rw-r--r-- 1 postgres postgres 2346 Apr 29 20:53 pgcrypto--1.2--1.3.sql -rw-r--r-- 1 postgres postgres 5708 Apr 29 20:53 pgcrypto--1.3.sql -rw-r--r-- 1 postgres postgres 152 Apr 29 20:53 pgcrypto.control ls -l uuid-ossp* -rw-r--r-- 1 postgres postgres 688 Apr 29 20:53 uuid-ossp--1.0--1.1.sql -rw-r--r-- 1 postgres postgres 1516 Apr 29 20:53 uuid-ossp--1.1.sql -rw-r--r-- 1 postgres postgres 178 Apr 29 20:53 uuid-ossp.control3.使用 pgcrypto 模块提供的 uuid 注: gen_random_uuid() 从 PostgreSQL 13 开始成为了一个内置函数 如果您所使用的PostgreSQL版本在13以上,则不需要执行如下语句: CREATE EXTENSION pgcrypto; 生成uuid: SELECT gen_random_uuid(); gen_random_uuid -------------------------------------- a7a5bf5a-715c-4d01-a915-bec09095cc9c (1 row) 如果想要生成没有中划线(-)的 UUID 字符串,可以使用 REPLACE 函数: SELECT replace(gen_random_uuid()::text,"-",""); replace ---------------------------------- 947997db3ddc4674b7ae54cbf0adc8bd (1 row)4.使用 uuid-ossp 模块提供的 uuidCREATE EXTENSION "uuid-ossp"; 查看包含的函数: df List of functions Schema | Name | Result data type | Argument data types | Type --------+--------------------+------------------+---------------------------+------ public | uuid_generate_v1 | uuid | | func public | uuid_generate_v1mc | uuid | | func public | uuid_generate_v3 | uuid | namespace uuid, name text | func public | uuid_generate_v4 | uuid | | func public | uuid_generate_v5 | uuid | namespace uuid, name text | func public | uuid_nil | uuid | | func public | uuid_ns_dns | uuid | | func public | uuid_ns_oid | uuid | | func public | uuid_ns_url | uuid | | func public | uuid_ns_x500 | uuid | | func 执行如下命令生成 uuid: select uuid_generate_v4(); uuid_generate_v4 -------------------------------------- 365f5708-f3b8-473f-b9ed-82888bfca4da (1 row) select upper(replace(uuid_generate_v4()::varchar, "-", "")); upper ---------------------------------- 968313D22E7E4EDBA9A9F786AA37DD60 (1 row)