Grant permissions to user for any new tables created in postgresql

后端 未结 3 867
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 17:28

Currently I am using this to grant permissions:

grant select on all tables in schema public to ;

alter default privileges in schema public          


        
相关标签:
3条回答
  • 2020-12-09 18:07

    I was looking for same thing, I found other way to solve this. Based on postgresql documentation we can create event trigger, so when new table is created, grant query will execute automatically. So no matter who created new table, other user allowed to use it.

    CREATE OR REPLACE FUNCTION auto_grant_func()
    RETURNS event_trigger AS $$
    BEGIN
        grant all on all tables in schema public to <username>;
        grant all on all sequences in schema public to <username>;
        grant select on all tables in schema public to <username>;
        grant select on all sequences in schema public to <username>;
    END;
    $$ LANGUAGE plpgsql;
    
    CREATE EVENT TRIGGER auto_grant_trigger
        ON ddl_command_end
        WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS')
    EXECUTE PROCEDURE auto_grant_func();
    
    0 讨论(0)
  • 2020-12-09 18:27

    Found the answer. It is in this line in the documentation.

    "You can change default privileges only for objects that will be created by yourself or by roles that you are a member of."

    I was using alter default privileges from a different user than the one creating the tables.

    0 讨论(0)
  • 2020-12-09 18:29

    To grant default privileges, you need to grant to the user you are creating the table with.

    You are creating the tables as SA_user, but reading the tables as READ_user. Your code needs to look like:

    ALTER DEFAULT PRIVILEGES 
    FOR USER SA_user
    IN SCHEMA schema_name
    GRANT SELECT ON TABLES TO READ_user;
    

    So whenever the SA_user creates a table, it will grant select rights for the READ_user.

    0 讨论(0)
提交回复
热议问题