在Postgres中为插入语句生成UUID?

本文介绍了在Postgres 8.4中如何为插入语句生成UUID,包括检查扩展是否存在、安装扩展、验证安装以及使用不同方法生成UUID。特别提到了uuid-ossp扩展和CREATE EXTENSION命令。

本文翻译自:Generating a UUID in Postgres for Insert statement?

My question is rather simple. 我的问题很简单。 I'm aware of the concept of a UUID and I want to generate one to refer to each 'item' from a 'store' in my DB with. 我知道UUID的概念,我想生成一个引用UDB的“存储”中的每个“项目”。 Seems reasonable right? 看起来合理吧?

The problem is the following line returns an error: 问题是以下行返回错误:

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.

I've read the page at: http://www.postgresql.org/docs/current/static/uuid-ossp.html 我已在以下位置阅读该页面: http : //www.postgresql.org/docs/current/static/uuid-ossp.html

在此处输入图片说明

I'm running Postgres 8.4 on Ubuntu 10.04 x64. 我在Ubuntu 10.04 x64上运行Postgres 8.4。


#1楼

参考:https://stackoom.com/question/qTA6/在Postgres中为插入语句生成UUID


#2楼

uuid-ossp is a contrib module, so it isn't loaded into the server by default. uuid-ossp是一个contrib模块,因此默认情况下不会加载到服务器中。 You must load it into your database to use it. 您必须将其加载到数据库中才能使用。

For modern PostgreSQL versions (9.1 and newer) that's easy: 对于现代PostgreSQL版本(9.1及更高版本),这很容易:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

but for 9.0 and below you must instead run the SQL script to load the extension. 但对于9.0及以下版本,您必须改为运行SQL脚本来加载扩展。 See the documentation for contrib modules in 8.4 . 请参阅8.4中的contrib模块文档

For Pg 9.1 and newer instead read the current contrib docs and CREATE EXTENSION . 对于Pg 9.1及更高版本,请阅读当前的contrib文档CREATE EXTENSION These features do not exist in 9.0 or older versions, like your 8.4. 这些功能在9.0或更早的版本(例如8.4)中不存在。

If you're using a packaged version of PostgreSQL you might need to install a separate package containing the contrib modules and extensions. 如果您使用的是PostgreSQL的打包版本,则可能需要安装包含contrib模块和扩展名的单独软件包。 Search your package manager database for 'postgres' and 'contrib'. 在软件包管理器数据库中搜索“ postgres”和“ contrib”。


#3楼

The answer by Craig Ringer is correct. Craig Ringer答案是正确的。 Here's a little more info for Postgres 9.1 and later… 这是Postgres 9.1及更高版本的更多信息……

Is Extension Available? 可以使用分机吗?

You can only install an extension if it has already been built for your Postgres installation (your cluster in Postgres lingo). 如果已为Postgres安装(您的集群使用Postgres术语)构建了扩展名,则只能安装该扩展名。 For example, I found the uuid-ossp extension included as part of the installer for Mac OS X kindly provided by EnterpriseDB.com. 例如,我发现uuid-ossp扩展包含在EnterpriseDB.com 提供的Mac OS X安装程序的一部分中。 Any of a few dozen extensions may be available. 几十个扩展中的任何一个都可用。

To see if the uuid-ossp extension is available in your Postgres cluster, run this SQL to query the pg_available_extensions system catalog: 要查看uuid-ossp扩展在Postgres集群中是否可用,请运行以下SQL查询pg_available_extensions系统目录:

SELECT * FROM pg_available_extensions;

Install Extension 安装扩展

To install that UUID -related extension, use the CREATE EXTENSION command as seen in this this SQL: 要安装与该UUID相关的扩展,请使用此SQL中所示的CREATE EXTENSION命令:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Beware: I found the QUOTATION MARK characters around extension name to be required, despite documentation to the contrary. 请注意:尽管有相反的说明,但我发现仍需要在扩展名周围使用QUOTATION MARK字符。

The SQL standards committee or Postgres team chose an odd name for that command. SQL标准委员会或Postgres团队为此命令选择了一个奇怪的名称。 To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION". 在我看来,他们应该选择“安装扩展”或“使用扩展”之类的东西。

Verify Installation 验证安装

You can verify the extension was successfully installed in the desired database by running this SQL to query the pg_extension system catalog: 您可以通过运行以下SQL查询pg_extension系统目录来验证该扩展程序是否已成功安装在所需的数据库中:

SELECT * FROM pg_extension;

UUID as default value UUID作为默认值

For more info, see the Question: Default value for UUID column in Postgres 有关更多信息,请参见Postgres中的“问题: UUID的默认值”列

The Old Way 旧方法

The information above uses the new Extensions feature added to Postgres 9.1. 上述用途的信息,新的附加功能添加到Postgres的9.1。 In previous versions, we had to find and run a script in a .sql file. 在以前的版本中,我们必须在.sql文件中查找并运行脚本。 The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extension for less work on the part of the user/consumer of the extension. 添加了扩展功能,以简化安装,为扩展创建者交易了更多的工作,而减少了扩展的用户/用户的工作。 See my blog post for more discussion. 请参阅我的博客文章以获取更多讨论。

Types of UUIDs UUID的类型

By the way, the code in the Question calls the function uuid_generate_v4() . 顺便说一句,Question中的代码调用了函数uuid_generate_v4() This generates a type known as Version 4 where nearly all of the 128 bits are randomly generated. 这将生成一种称为版本4的类型,其中几乎所有128位都是随机生成的。 While this is fine for limited use on smaller set of rows, if you want to virtually eliminate any possibility of collision, use another "version" of UUID. 尽管这对于限制在较小的行集上的有限使用是很好的,但是如果您想消除冲突的可能性,请使用UUID的另一个“版本”。

For example, the original Version 1 combines the MAC address of the host computer with the current date-time and an arbitrary number, the chance of collisions is practically nil. 例如,原始版本1将主机的MAC地址与当前日期时间和任意数字结合在一起,发生冲突的机会几乎为零。

For more discussion, see my Answer on related Question. 有关更多讨论,请参见对相关问题的回答


#4楼

Without extensions (cheat) 没有扩展名(作弊)

SELECT uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);

output>> c2d29867-3d0b-d497-9191-18a9d8ee7830

(works at least in 8.4) (至少在8.4中有效)

  • Thanks to @Erwin Brandstetter for clock_timestamp() explanation. 感谢@Erwin Brandstetter提供的clock_timestamp()解释。

If you need a valid v4 UUID 如果您需要有效的v4 UUID

SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring);

在此处输入图片说明 * Thanks to @Denis Stafichuk @Karsten and @autronix *感谢@Denis Stafichuk @Karsten@autronix


Also, in modern Postgres, you can simply cast: 另外,在现代Postgres中,您可以简单地进行以下转换:

SELECT md5(random()::text || clock_timestamp()::text)::uuid


#5楼

pgcrypto Extension pgcrypto扩展

As of Postgres 9.4, the pgcrypto module includes the gen_random_uuid() function. 从Postgres 9.4开始, pgcrypto模块包括gen_random_uuid()函数。 This function generates one of the random-number based Version 4 type of UUID . 此函数生成基于随机数的UUID版本4类型之一

Get contrib modules, if not already available. 获取contrib模块(如果尚不可用)。

sudo apt-get install postgresql-contrib-9.4

Use pgcrypto module. 使用pgcrypto模块。

CREATE EXTENSION "pgcrypto";

The gen_random_uuid() function should now available; gen_random_uuid()函数现在应该可用;

Example usage. 用法示例。

INSERT INTO items VALUES( gen_random_uuid(), 54.321, 31, 'desc 1', 31.94 ) ;


Quote from Postgres doc on uuid-ossp module. uuid-ossp模块引用Postgres文档

Note: If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead. 注意:如果只需要随机生成的(版本4)UUID,请考虑使用pgcrypto模块中的gen_random_uuid()函数。


#6楼

ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);

阅读@ZuzEL的答案后,我将上面的代码用作列ID的默认值,并且工作正常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值