强制约束名称唯一性

amp*_*ent 1 postgresql

我刚刚注意到 PostgreSQL 允许在数据库中重复外键(以及可能的其他约束)名称,只要它们位于不同的表上即可。

因此,如果父表是并且Foo它有两个子表,则两个表上的外键都可以命名。BarXBarYFK_fooid

在我看来,这是一个糟糕的设计,因为

select * from information_schema.referential_constraints
where constraint_name = 'FK_fooid' 
Run Code Online (Sandbox Code Playgroud)

将返回两行相同的行,无法区分哪一行对应于哪个表/键。

有没有办法在 Postgres 中的数据库中禁用约束名称的重复,并强制每个约束都有唯一的名称?

小智 5

将返回两个相同的行,无法区分哪一行对应于哪个表/键。

那么不要使用information_schema

select nsp.nspname as constraint_schema,
       c.conname as constraint_name,  
       format('%I.%I', ts.nspname, t.relname) as target_table,
       pg_get_constraintdef(c.oid) as constraint_definition
from pg_class t 
  join pg_constraint c on t.oid = c.conrelid   
  join pg_namespace nsp on t.relnamespace = nsp.oid 
  join pg_namespace ts on t.relnamespace = ts.oid
where c.contype in ('f') 
 and c.conname = 'fk_fooid';
Run Code Online (Sandbox Code Playgroud)

示例: http: //rextester.com/DAR30737