PostgreSQL 13: 新增内置函数Gen_random_uuid()生成UUID数据

手册说明

Add function gen_random_uuid() to generate version 4 UUIDs (Peter Eisentraut)

Previously UUID generation functions were only available via external modules uuid-ossp and pgcrypto.

PostgreSQL 13版本前不提供生成UUID数据的内置函数,如果需要使用UUID数据,可通过创建外部扩展 uuid-ossppgcrypto生成 UUID数据。

PostgreSQL 13 新增gen_random_uuid()内置函数,可生成UUID数据。

关于gen_random_uuid()函数

gen_random_uuid()函数生成 version 4 UUID(基于随机数生成,使用最广泛)。

一个示例,如下:

1
2
3
4
5
6
7
8
9
10
11
postgres=# \df gen_random_uuid
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+-----------------+------------------+---------------------+------
pg_catalog | gen_random_uuid | uuid | | func
(1 row)

postgres=# SELECT gen_random_uuid();
gen_random_uuid
--------------------------------------
e5194f5d-0602-4a88-b388-c3bd7bfd570e

生成一张包含UUID数据的表

PostgreSQL 提供 UUID数据类型,在UUID数据上可创建btree索引,下面演示下。

创建测试表并生成UUID数据,之后创建索引,如下:

1
2
3
4
5
6
7
8
mydb=> CREATE TABLE uuid_01(id_int int4, id_uuid uuid,ctime timestamp(6) without time zone);
CREATE TABLE

mydb=> INSERT INTO uuid_01(id_int,id_uuid,ctime) SELECT n,gen_random_uuid(),clock_timestamp() FROM generate_series(1,2000000) n;
INSERT 0 2000000

mydb=> CREATE UNIQUE INDEX idx_uuid_01_uuid ON uuid_01 USING BTREE (id_uuid);
CREATE INDEX

查看UUID数据和执行计划,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mydb=> SELECT *FROM uuid_01 LIMIT 1;
id_int | id_uuid | ctime
--------+--------------------------------------+----------------------------
1 | 3ba43653-e470-40d9-bfc0-55d33677ec22 | 2020-07-08 21:10:39.010639
(1 row)

mydb=> EXPLAIN ANALYZE SELECT *FROM uuid_01 WHERE id_uuid='3ba43653-e470-40d9-bfc0-55d33677ec22';
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
Index Scan using idx_uuid_01_uuid on uuid_01 (cost=0.43..4.45 rows=1 width=28) (actual time=0.027..0.029 rows=1 loops=1)
Index Cond: (id_uuid = '3ba43653-e470-40d9-bfc0-55d33677ec22'::uuid)
Planning Time: 0.162 ms
Execution Time: 0.059 ms
(4 rows)

参考

最后推荐和张文升共同编写的《PostgreSQL实战》,本书基于PostgreSQL 10 编写,共18章,重点介绍SQL高级特性、并行查询、分区表、物理复制、逻辑复制、备份恢复、高可用、性能优化、PostGIS等,涵盖大量实战用例!

购买链接:https://item.jd.com/12405774.html

PostgreSQL实战
感谢支持!
0%