List constraints for all tables with different owners in PostgreSQL

爷,独闯天下 提交于 2019-12-03 05:38:51

Not all constraint-related data is "protected". You use three relations in your query:

  • table_constraints
  • key_column_usage
  • constraint_column_usage

The first two are not limited, but the documentation for constraint_column_usage tells you:

The view constraint_column_usage identifies all columns in the current database that are used by some constraint. Only those columns are shown that are contained in a table owned by a currently enabled role.

Since information_schema.constraint_column_usage is a view, you can see its definition using

\d+ information_schema.constraint_column_usage

in the psql shell. The result looks frightening at a first glance but it's really not so bad. The most interesting thing - for a first test - is the part in the very last line:

  WHERE pg_has_role(x.tblowner, 'USAGE'::text);

If you paste the definition into the psql shell which is open by the non-owner rights_test_role and delete that last line you will get the desired result. This is good, because that means that the basic metadata is not protected by the system. So you can strip down the view definition to include only the parts you really need.

Anupama Boorlagadda

Try using this.. gives all the constraint names and constraint description.

  • Foreign key
  • Check
  • Primary key
  • Unique

Like:

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

To list relational constraints you can use next query:

SELECT
    tc.constraint_name, tc.table_name, kcu.column_name, 
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!