Search code examples
postgresqluser-roles

how to create duplicate role of a user in postgres


I need a new user but it should be granted all those privileges that the other existing user/role has.

e.g.

  • User A has SELECT privileges on Table1
  • User A has EXECUTE privileges on Table2
  • ...

If a new User B is created, I need the same privileges as,

  • User B has SELECT privileges on Table1
  • User B has EXECUTE privileges on Table2
  • ...

Dont ask why :/

Actually User A has custom privileges on different tables, schemas, and functions; so its very tedious and lengthy process to manually grant permissions to the new user. Any help would be good.


Solution

  • I had to write the pgpsql code to loop through the privileges of User A and grant it to User B. It was done without any problem.

    create or replace function update_user_privileges() returns text as
    $$
    declare
    
           info record;
           str text;
    
    begin
           /*Grant privileges to user B the same as with user A for a given table schema*/
          str:=''; 
          FOR info IN 
              select * from information_schema.table_privileges where table_schema='public' and grantee = 'A'   
          LOOP 
              /*append the tables' name, for which we are assigning privileges from user A to B*/
              str:= str  ||info.table_name || ',';
    
             /*this is the main statement to grant any privilege*/
             execute 'GRANT '|| info.privilege_type ||' on table public.'|| info.table_name || ' to B';
    
          END LOOP;
    
      return str;
    end
    
    $$ language 'plpgsql';
    

    Usage: Copy/paste this code to crate this function and then do

    select update_user_privileges();
    

    **You have to adapt it for your table-schema and table-names. Hope it helps anyone