Do I have to be owner of relation to access constraint related data in information schema? I've tested the following and it seems that I have to be the owner.
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
*/
Is there other way how to get the same information if I am not owner of the relation?
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.