Skip to content
Advertisement

Grant on dynamic database name in Postgresql

I am trying to grant a new user permissions on the current database (whose name I do not know).

Basically I want to archive something like this:

grant all privileges on database $(SELECT current_database();) to my_new_user;

Any hints how this could be achieved?

Advertisement

Answer

You cannot combine GRANTs with queries directly, but you may write a small block to achieve that. Since GRANT allows only database names and no variables, you have to create the command as string and execute it with EXECUTE:

DO $_$
    DECLARE
        the_database TEXT := CURRENT_DATABASE();
    BEGIN
        EXECUTE FORMAT('GRANT ALL PRIVILEGES ON DATABASE %s TO my_new_user', the_database);
    END
$_$;

Addendum: If the database name might contain special characters like dashes you should put the name into double quotes:

DO $_$
    DECLARE
        the_database TEXT := CURRENT_DATABASE();
    BEGIN
        EXECUTE FORMAT('GRANT ALL PRIVILEGES ON DATABASE %I TO my_new_user', the_database);
    END
$_$;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement