Search code examples
sqlpostgresqluser-roles

Selecting groups name of current_user


I use the following command to check the groups or roles of a user in a PostgreSQL database,

select rolname from pg_authid where pg_has_role('some_username', rolname, 'member');

As seen, I have to manually type the user name in above query, like 'some_username' above.

Is there a way I can query it for the current_user, I mean for the user who is curently connected with the database. Something like command below,

select rolname from pg_authid where pg_has_role(current_user, rolname, 'member'); 

This command doesn't work properly. It returns complete rolname column from pg_authid.


Solution

  • To access pg_authid you need to be superuser, and therefor current_user will be the superuser and that one has all the roles.

    To get that information when you are logged in with a non-superuser, use pg_roles

    Quote from the manual for pg_roles

    This is simply a publicly readable view of pg_authid that blanks out the password field.

    select rolname 
    from pg_roles 
    where pg_has_role(current_user, rolname, 'member');