PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Elencare grant e privilegi di una vista materializzata in PostgreSQL

In PostgreSQL i cataloghi di sistema sono la fonte di informazione più affidabile sull'installazione e sui database. L'information schema è solo uno strato aggiuntivo, costruito sui cataloghi per garantire compatibilità con altri RDBMS.

Le viste materializzate non sono oggetti standard SQL, quindi l'information schema non contiene informazioni su di esse.

Dove trovare i privilegi

Il catalogo pg_class conserva tutti i privilegi nella colonna relacl:

  • se la colonna è NULL, il proprietario ha tutti i privilegi;
  • una stringa vuota come nome utente nell'ACL indica public.
create materialized view test_view as select 1;
grant select on test_view to public;
grant delete on test_view to a_user;

select coalesce(nullif(s[1], ''), 'public') as grantee, s[2] as privileges
from pg_class c
  join pg_namespace n on n.oid = relnamespace
  join pg_roles r on r.oid = relowner,
  unnest(coalesce(relacl::text[], format('{%s=arwdDxt/%s}', rolname, rolname)::text[])) acl,
  regexp_split_to_array(acl, '=|/') s
where nspname = 'public' and relname = 'test_view';

grantee  | privileges
---------+------------
postgres | arwdDxt
public   | r
a_user   | d
(3 rows)

Formato leggibile

Per visualizzare i privilegi in forma estesa serve una funzione di supporto:

create or replace function priviliges_from_acl(text) returns text language sql as $$
select string_agg(privilege, ', ') from (
  select case ch
    when 'r' then 'SELECT'
    when 'w' then 'UPDATE'
    when 'a' then 'INSERT'
    when 'd' then 'DELETE'
    when 'D' then 'TRUNCATE'
    when 'x' then 'REFERENCES'
    when 't' then 'TRIGGER'
  end privilege
  from regexp_split_to_table($1, '') ch
) s
$$;

Si usa così:

select coalesce(nullif(s[1], ''), 'public') as grantee, priviliges_from_acl(s[2]) as privileges
from pg_class c
  join pg_namespace n on n.oid = relnamespace
  join pg_roles r on r.oid = relowner,
  unnest(coalesce(relacl::text[], format('{%s=arwdDxt/%s}', rolname, rolname)::text[])) acl,
  regexp_split_to_array(acl, '=|/') s
where nspname = 'public' and relname = 'test_view';

grantee  | privileges
---------+---------------------------------------------------------------
postgres | INSERT, SELECT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
public   | SELECT
a_user   | DELETE
(3 rows)