列出PostgreSQL中具有不同所有者的所有表的约束

Tom*_*eif 13 postgresql postgresql-9.1

我必须是信息模式中访问约束相关数据的关系的所有者吗?我测试了以下内容,似乎我必须是主人.

create schema rights_test;

create table rights_test.t1 (id int primary key);
create table rights_test.t2 (id int references rights_test.t1(id));

select  
        tc.constraint_name, 
        tc.constraint_schema || '.' || tc.table_name || '.' || kcu.column_name as physical_full_name,  
        tc.constraint_schema,
        tc.table_name, 
        kcu.column_name, 
        ccu.table_name as foreign_table_name, 
        ccu.column_name as foreign_column_name,
        tc.constraint_type
    from 
        information_schema.table_constraints as tc  
        join information_schema.key_column_usage as kcu on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name)
        join information_schema.constraint_column_usage as ccu on ccu.constraint_name = tc.constraint_name
    where 
        constraint_type in ('PRIMARY KEY','FOREIGN KEY')
        and tc.constraint_schema = 'rights_test'

/*
This will produce desired output:
t1_pkey;rights_test.t1.id;rights_test;t1;id;t1;id;PRIMARY KEY
t2_id_fkey;rights_test.t2.id;rights_test;t2;id;t1;id;FOREIGN KEY
*/

create user rights_test_role with password 'password';

grant all on rights_test.t1 to rights_test_role;
grant all on rights_test.t2 to rights_test_role;

/* Now login as rights_test_role and try the same constraint select.
   For rights_test_role it returns nothing although I've added ALL privileges
*/
Run Code Online (Sandbox Code Playgroud)

如果我不是关系的所有者,还有其他方法可以获得相同的信息吗?

Anu*_*dda 20

尝试使用此..给出所有约束名称和约束描述.

  • 外键
  • 校验
  • 首要的关键
  • 独特

喜欢:

select conrelid::regclass AS table_from, conname, pg_get_constraintdef(c.oid)
from   pg_constraint c
join   pg_namespace n ON n.oid = c.connamespace
where  contype in ('f', 'p','c','u') order by contype
Run Code Online (Sandbox Code Playgroud)


A.H*_*.H. 9

并非所有与约束相关的数据都是"受保护的".您在查询中使用三个关系:

  • table_constraints
  • key_column_usage
  • constraint_column_usage

前两个不受限制,但文档constraint_column_usage告诉您:

视图constraint_column_usage标识当前数据库中某些约束使用的所有列.仅显示包含在当前启用的角色所拥有的表中的那些列.

既然information_schema.constraint_column_usage是视图,您可以使用它来查看其定义

\d+ information_schema.constraint_column_usage
Run Code Online (Sandbox Code Playgroud)

在psql shell中.结果看起来很乍看,但实际上并没有那么糟糕.最有趣的事情 - 第一次测试 - 是最后一行中的部分:

  WHERE pg_has_role(x.tblowner, 'USAGE'::text);
Run Code Online (Sandbox Code Playgroud)

如果将定义粘贴到非所有者打开的psql shell中rights_test_role并删除最后一行,您将获得所需的结果.这很好,因为这意味着基本元数据不受系统保护.因此,您可以删除视图定义以仅包含您真正需要的部分.

  • `\ d +`是你的朋友. (2认同)