PostgreSQL:默认约束名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4107915/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:43:21  来源:igfitidea点击:

PostgreSQL: default constraint names

postgresqlnaming-conventionsconstraints

提问by Ian Mackinnon

When creating a table in PostgreSQL, default constraint names will assigned if not provided:

在 PostgreSQL 中创建表时,如果未提供,将分配默认约束名称:

CREATE TABLE example (
    a integer,
    b integer,
    UNIQUE (a, b)
);

But using ALTER TABLEto add a constraint it seems a name is mandatory:

但是使用ALTER TABLE添加约束似乎名称是强制性的:

ALTER TABLE example ADD CONSTRAINT my_explicit_constraint_name UNIQUE (a, b);

This has caused some naming inconsistencies on projects I've worked on, and prompts the following questions:

这在我参与的项目中造成了一些命名不一致,并提示以下问题:

  1. Is there a simple way to add a constraint to an extant table with the name it would have received if added during table creation?

  2. If not, should default names be avoided altogether to prevent inconsistencies?

  1. 是否有一种简单的方法可以将约束添加到现有表中,其名称是在表创建期间添加时会收到的名称?

  2. 如果不是,是否应该完全避免默认名称以防止不一致?

采纳答案by a_horse_with_no_name

The manualis pretty clear about this ("tableconstraint: This form adds a new constraint to a table using the same syntax as CREATE TABLE.")

手册是关于这很清楚(“ tableconstraint:这种形式使用相同的语法增加了一个新的约束,一个表作为CREATE TABLE。”)

So you can simply run:

所以你可以简单地运行:

ALTER TABLE example ADD UNIQUE (a, b);

回答by Frank Heikens

The standard names for indexes in PostgreSQL are:

PostgreSQL 中索引的标准名称是:

{tablename}_{columnname(s)}_{suffix}

{tablename}_{columnname(s)}_{suffix}

where the suffix is one of the following:

其中后缀是以下之一:

  • pkeyfor a Primary Key constraint
  • keyfor a Unique constraint
  • exclfor an Exclusion constraint
  • idxfor any other kind of index
  • fkeyfor a Foreign key
  • checkfor a Check constraint
  • pkey对于主键约束
  • key对于唯一约束
  • excl对于排除约束
  • idx对于任何其他类型的索引
  • fkey对于外键
  • check对于 Check 约束

Standard suffix for sequences is

序列的标准后缀是

  • seqfor all sequences
  • seq对于所有序列

Proof of your UNIQUE-constraint:

证明您的 UNIQUE 约束:

NOTICE: CREATE TABLE / UNIQUE will create implicit index "example_a_b_key" for table "example"

注意:CREATE TABLE / UNIQUE 将为表“example”创建隐式索引“example_a_b_key”