postgresql - 为什么不在公共(public)架构中的约束不可见?

标签 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;

最佳答案

Now, when I query information_schema.table_constraints, the index is not shown

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 - 索引

关于postgresql - 为什么不在公共(public)架构中的约束不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50113073/

相关文章:

django - Postgis/Geodjango : Cannot determine PostGIS version for database

database - pg_restore : [compress_io] could not uncompress data: invalid code lengths set

python - 密码验证失败,密码复杂

sql - 您如何对编码或加密数据进行 PostgreSQL 全文搜索?

python - SELECT 被 OS 信号中断后 Psycopg2 连接不可用

PostgreSQL Schema 长度和 Search_Path

python - Postgres 服务器如何知道保持数据库连接打开

perl - 如何从另一个 PL/Perl 函数调用 PL/Perl 函数?

python - 如何使用 Django 加速 PostgreSQL 数据库中的正则表达式查询

python - 带有 timescaledb 扩展的 postgresql 的 SQLalchemy 设置