postgresql 在 Postgres 中为 Insert 语句生成 UUID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12505158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating a UUID in Postgres for Insert statement?
提问by anon58192932
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. Seems reasonable right?
我的问题比较简单。我知道 UUID 的概念,我想生成一个来引用数据库中“商店”中的每个“项目”。看起来合理吧?
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。
回答by Craig Ringer
uuid-ossp
is a contrib module, so it isn't loaded into the server by default. You must load it into your database to use it.
uuid-ossp
是一个 contrib 模块,因此默认情况下它不会加载到服务器中。您必须将其加载到数据库中才能使用它。
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. See the documentation for contrib modules in 8.4.
但是对于 9.0 及以下版本,您必须改为运行 SQL 脚本来加载扩展。请参阅8.4 中的 contrib 模块的文档。
For Pg 9.1 and newer instead read the current contrib docsand CREATE EXTENSION
. These features do not exist in 9.0 or older versions, like your 8.4.
对于 Pg 9.1 和更新版本,请阅读当前的 contrib 文档和CREATE EXTENSION
. 这些功能在 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. Search your package manager database for 'postgres' and 'contrib'.
如果您使用的是 PostgreSQL 的打包版本,您可能需要安装一个单独的包,其中包含 contrib 模块和扩展。在包管理器数据库中搜索“postgres”和“contrib”。
回答by ZuzEL
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@Karstenand @autronix
* 感谢@Denis Stafichuk @Karsten和@autronix
Also, in modern Postgres, you can simply cast:
此外,在现代 Postgres 中,您可以简单地转换:
SELECT md5(random()::text || clock_timestamp()::text)::uuid
SELECT md5(random()::text || clock_timestamp()::text)::uuid
回答by Basil Bourque
The answer by Craig Ringeris correct. Here's a little more info for Postgres 9.1 and later…
Craig Ringer的回答是正确的。这是 Postgres 9.1 及更高版本的更多信息……
Is Extension Available?
扩展是否可用?
You can only install an extension if it has already been built for your Postgres installation (your clusterin Postgres lingo). For example, I found the uuid-osspextension included as part of the installer for Mac OS X kindly providedby EnterpriseDB.com. Any of a few dozen extensionsmay be available.
如果扩展已经为您的 Postgres 安装(Postgres 行话中的集群)构建,则您只能安装它。例如,我发现uuid-ossp扩展包含在EnterpriseDB.com提供的Mac OS X 安装程序中。可能有几十个扩展中的任何一个可用。
To see if the uuid-osspextension 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 EXTENSIONcommand 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.
当心:我发现扩展名周围的引号字符是必需的,尽管文档相反。
The SQL standards committee or Postgres team chose an odd name for that command. To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION".
SQL 标准委员会或 Postgres 团队为该命令选择了一个奇怪的名称。在我看来,他们应该选择“安装扩展”或“使用扩展”之类的东西。
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 Extensionsfeature addedto Postgres 9.1. In previous versions, we had to find and run a script in a .sqlfile. The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extensionfor less work on the part of the user/consumer of the extension. See my blog postfor more discussion.
以上信息使用了添加到 Postgres 9.1的新扩展功能。在以前的版本中,我们必须在.sql文件中查找并运行脚本。添加了扩展功能是为了使安装更容易,为扩展的创建者提供更多的工作,而扩展的用户/消费者则需要更少的工作。有关更多讨论,请参阅我的博客文章。
Types of UUIDs
UUID 的类型
By the way, the code in the Question calls the function uuid_generate_v4()
. This generates a type known as Version 4where nearly all of the 128 bits are randomly generated. 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_generate_v4()
。这会生成一种称为版本 4的类型,其中几乎所有 128 位都是随机生成的。虽然这对于在较小的行集上有限使用是很好的,但如果您想几乎消除任何冲突的可能性,请使用另一个“版本”的 UUID。
For example, the original Version 1combines the MAC addressof 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 Answeron related Question.
回答by brillout
pgcrypto
Extension
pgcrypto
延期
As of Postgres 9.4, the pgcrypto
module includes the gen_random_uuid()
function. This function generates one of the random-number based Version 4 type of UUID.
从 Postgres 9.4 开始,该pgcrypto
模块包含该gen_random_uuid()
功能。此函数生成基于随机数的第 4 版 UUID 类型之一。
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.
引用来自Postgres 文档的uuid-ossp
模块。
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() 函数。
回答by Paolo Fernandes
ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);
After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.
阅读@ZuzEL 的回答后,我使用上面的代码作为列 id 的默认值,它工作正常。
回答by Lukasz Szozda
Upcoming PostgreSQL 13 will support natively gen_random_uuid ()without need to enable any extensions:
即将发布的 PostgreSQL 13 将原生支持gen_random_uuid(),无需启用任何扩展:
PostgreSQL includes one function to generate a UUID:
gen_random_uuid () → uuid
This function returns a version 4 (random) UUID. This is the most commonly used type of UUID and is appropriate for most applications.
PostgreSQL 包括一个生成 UUID 的函数:
gen_random_uuid () → uuid
此函数返回版本 4(随机)UUID。这是最常用的 UUID 类型,适用于大多数应用程序。