为什么不在公共模式中的约束不可见?

时间:2018-05-01 07:50:59

标签: postgresql

我正在模式中创建一个具有唯一索引的表,如下所示:

create schema s1;
create table s1.test(key int);
create unique index test_index on s1.test(key);

现在,当我查询information_schema.table_constraints时,索引不会显示。这是为什么?但是,索引正常工作:

test=# insert into s1.test(key) values (1);
INSERT 0 1
test=# insert into s1.test(key) values (1);
ERROR:  duplicate key value violates unique constraint "test_index"
DETAIL:  Key (key)=(1) already exists.

我在这里使用的数据库test由当前用户拥有。

更新

看起来约束也没有显示在public架构中:

create table test(key int);
create unique index test_index on test(key);
select * from information_schema.table_constraints;

1 个答案:

答案 0 :(得分:3)

  

现在,当我查询information_schema.table_constraints时,索引未显示

UNIQUE INDEX!= CONSTRAINT您需要添加CONSTRAINT

ALTER TABLE test ADD CONSTRAINT uq_test_key UNIQUE(key);

-- constraint info
SELECT *
FROM information_schema.table_constraints;


-- supportive index info
select
 t.relname as table_name,
 i.relname as index_name,
 a.attname as column_name
from
 pg_class t,
 pg_class i,
 pg_index ix,
 pg_attribute a
where
 t.oid = ix.indrelid
 and i.oid = ix.indexrelid
 and a.attrelid = t.oid
 and a.attnum = ANY(ix.indkey)
 and t.relkind = 'r'
 and t.relname = 'test';

DBFiddle Demo CONSTRAINT - 约束+索引

DBFiddle Demo INDEX ONLY - 索引