PostgreSQL安装uuid-ossp
我们有时候需要像Oracle或MySQL那样可以通过函数sys_guid()或uuid()来获得uuid,如:bdf7eb80-776f-11eb-b4e3-0800277427f4。
默认postgresql并没有该功能,但是可以通过扩展uuid-ossp来实现。
我们可以通过以下命令查看已有的扩展:
postgres=# select * from pg_extension;
oid | extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition
-------+---------+----------+--------------+----------------+------------+-----------+--------------
13579 | plpgsql | 10 | 11 | f | 1.0 | |
(1 row)
或
postgres=# \dx
List of installed extensions
Name | Version | Schema | Description
---------+---------+------------+------------------------------
plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language
(1 row)
可以看到postgresql目前没有安装uuid-ossp扩展。
查看当前可用的扩展:
postgres=# select * from pg_available_extensions;
name | default_version | installed_version | comment
------------+-----------------+-------------------+-------------------------------------------
plpgsql | 1.0 | 1.0 | PL/pgSQL procedural language
plperl | 1.0 | | PL/Perl procedural language
plperlu | 1.0 | | PL/PerlU untrusted procedural language
plpython2u | 1.0 | | PL/Python2U untrusted procedural language
plpythonu | 1.0 | | PL/PythonU untrusted procedural language
(5 rows)
可以看到postgres目前并没有可用的uuid-ossp扩展。
此时,直接创建uuid-ossp会报错,如:
postgres=# create extension "uuid-ossp";
ERROR: could not open extension control file "/opt/pgsql12.2/share/extension/uuid-ossp.control": No such file or directory
注意:
要用双引号将uuid-ossp引起来,因为有个中划线“-”。否则:
postgres=# create extension uuid-ossp;
ERROR: syntax error at or near "-"
LINE 1: create extension uuid-ossp;
^
[root@Location-01 ~]# yum -y install e2fsprogs-devel uuid uuid-devel libuuid-devel
[root@Location-01 ~]# cd /usr/local/src/postgresql-12.2/
[root@Location-01 postgresql-12.2]# pwd
/usr/local/src/postgresql-12.2
[root@Location-01 postgresql-12.2]# ./configure --prefix=/opt/pgsql12.2 --with-uuid=ossp
进入扩展目录:
[root@Location-01 ~]# cd /usr/local/src/postgresql-12.2/contrib/uuid-ossp/
[root@Location-01 uuid-ossp]# pwd
/usr/local/src/postgresql-12.2/contrib/uuid-ossp
执行编译安装:
[root@Location-01 uuid-ossp]# make && make install
postgres=# select * from pg_available_extensions;
name | default_version | installed_version | comment
------------+-----------------+-------------------+-------------------------------------------------
plpgsql | 1.0 | 1.0 | PL/pgSQL procedural language
plperl | 1.0 | | PL/Perl procedural language
plperlu | 1.0 | | PL/PerlU untrusted procedural language
plpython2u | 1.0 | | PL/Python2U untrusted procedural language
plpythonu | 1.0 | | PL/PythonU untrusted procedural language
uuid-ossp | 1.1 | | generate universally unique identifiers (UUIDs)
(6 rows)
可以看到已经有扩展uuid-ossp了。下面可以创建了。
postgres=# create extension "uuid-ossp";
CREATE EXTENSION
创建成功。
安装扩展成功以后,就可以使用函数uuid_generate_v4()来生产uuid了。
postgres=# select uuid_generate_v4();
uuid_generate_v4
--------------------------------------
cba03532-aa87-40be-b4e2-cf2e13b71c6e
(1 row)
如果你只需要随机生成的(版本4)UUIDs,请考虑使用pgcrypto组件中的 gen_random_uuid()函数来替代。