本文翻译自: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的默认值,并且工作正常。

在Postgres中为插入语句生成UUID?相关推荐

  1. php插入语句,请教关于php中sql插入语句的问题。

    问题代码如下:error_reporting(E_ALL ^ E_NOTICE); //包含excel读取类文件 require_once 'excel_reader2.php'; $data = n ...

  2. oracle表中增加字段 sql语句,ORACLE中通过SQL语句(alter table)来增加、删除、修改字段...

    1.添加字段: alter table  表名  add (字段  字段类型)  [ default  '输入默认值']  [null/not null]  ; 2.添加备注: comment on ...

  3. Java生成UUID的常用方式

    java.util.UUID类来生成UUID import java.util.UUID;public class UUIDGenerator {public static void main(Str ...

  4. 动态生成多条插入语句 存入文本文档中

    写一个程序,能够动态生成多条插入语句如:insert into MyStudents values("人名1",年龄,'男',分数1,分数2).将生成的插入语句输出到记事本文件 S ...

  5. SQL语句中生成UUID方法

    原文:SQL语句中生成UUID方法 SQL语句中生成UUID方法为UUID() 生成带横线UUID: select UUID()                         形如:abaffaca ...

  6. 格式化测试数据,组装用于插入表中的sql语句

    最近闲的蛋疼,每每在写测试例子的时候,万恶的测试数据需要手工书写insert语句的向表中插入,很费事,于是就像写个脚本来实现自动生成插入语句 测试数据: 100 北京 20120203123 100 ...

  7. SQL语句oracle中如何插入Date类型的数据

    在开发的时候,经常要写条SQL语句将信息插入表中,插入的数据如果字段是date类型,就必须将date类型转换成字符串String类型在通过sql语句插入数据库.这是我字段唯一的方法,如果有高人请另赐教 ...

  8. mybatis 增删改查、批量插入和删除以及自动生成uuid主键和分页

    Mapper接口: public int update(Admin admin); public Admin selectByUserName(String account); public List ...

  9. 动态生成多条插入语句

    写一个程序,能够动态生成多条插入语句如:insert into MyStudents values("人名1",年龄,'男',分数1,分数2).将生成的插入语句输出到记事本文件 S ...

最新文章

  1. 设计模式(策略模式)
  2. Swift游戏实战-跑酷熊猫 01 创建工程导入素材
  3. 【7】jQuery学习——入门jQuery选择器之过滤选择器-可见性过滤选择器
  4. CountDownLatch原理简介和使用过程
  5. Sql Server的艺术(二) SQL复杂条件搜索
  6. MATLAB 二脉冲对消、重频参差滤波器设计仿真
  7. 详解ISA2006的三种客户端模式
  8. python绘制立体扇形_你不知道的4种方法:python方法绘制扇形
  9. 孙鑫VC学习笔记:第十三讲 (四) 生成可串行化的类
  10. 全球与中国调频广播发射机市场深度研究分析报告
  11. 企业网的规划与设计(eNSP)
  12. LOJ3049 [十二省联考2019] 字符串问题 【后缀自动机】【倍增】【拓扑排序】
  13. 如何上传大文件(4GB)到虚拟机
  14. python循环计算水仙花数_我想用python编个小程序,循环计算用户给处的任意两个整数之间的水仙花数。...
  15. 机房收费管理系统之退卡
  16. 创业者、如何可以投资小,又可以依附互联网去创业?
  17. The system cannot find the path specified
  18. 分享一款多功能免费SEO工具箱-从0开始打造高流量网站
  19. 计算机原理及硬件,计算机原理及硬件介绍
  20. springcloud 项目maven依赖:Failure to find org.springframework.cloud:spring-cloud-dependencies

热门文章

  1. 在android布局中使用include和merge标签
  2. OpenGL学习总结
  3. Ubuntu 18启动失败 Started Hold until boot procss finishes up
  4. NLP(二十八)多标签文本分类
  5. JavaScript语言基础3
  6. Android View绘制之旅
  7. Dart Metadata 使用
  8. NSPredicate的使用
  9. iOS的类方法和实例方法区别与使用
  10. elasticsearch创建mysql索引_ElasticSearch快速使用,基本索引创建-增加type-mapping-插入数据...