在Postgres中生成用于INSERT语句的UUID?

630

我的问题很简单。我知道UUID的概念,并希望生成一个UUID来指代我的数据库中店铺中的每个“项目”。听起来很合理吧?

问题是以下这行代码会返回错误:

honeydb=# insert into items values(
uuid_generate_v4(), 54.321, 31, 'desc 1', 31.94);
ERROR:  function uuid_generate_v4() does not exist
LINE 2: uuid_generate_v4(), 54.321, 31, 'desc 1', 31.94);
        ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

我已阅读页面:http://www.postgresql.org/docs/current/static/uuid-ossp.html

我的操作系统是Ubuntu 10.04 x64,正在运行Postgres 8.4。


18
Postgres原生支持UUID作为数据类型,甚至可以作为索引和主键使用。但是要生成UUID值,例如为列建立默认值,您需要一个Postgres扩展(插件)。许多Postgres发布版本包括这样的扩展,但不会激活该扩展。请参见Craig Ringer的正确答案,了解如何激活它。 - Basil Bourque
4
如果您已经安装了uuid-ossp并且仍然遇到此错误,请尝试在函数前加上模式名称,例如:select dbo.uuid_generate_v4() - Richard
如果您想让Postgres为PK(主键)之外的列生成UUID,我终于找到了一种特定的方法:https://dev59.com/HvTvpIgB1922wOYJZ-k9#75900798 - chaotic3quilibrium
2
如果您使用的是Postgres 13+版本,无需安装扩展,只需调用gen_random_uuid()函数即可。
来源:https://dev59.com/a2cs5IYBdhLWcg3w433H#61970869
- Jahan Zinedine
12个回答

2
首先,你需要添加扩展
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-3
SELECT uuid_generate_v5(uuid_ns_url (), 'test');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接