grant usage & privileges on future created schema in PostgreSQL

耗尽温柔 提交于 2019-12-23 09:57:09

问题


The application I am integrating now will create new schemas. (each customer has its owned schema, eg. schema1, schema2, schema3 ....etc) To grant usage and read-only access to the new created schema and specific tables in the schema, I execute these commands:

GRANT USAGE ON SCHEMA schema1 TO read_only_user;
GRANT SELECT ON schema1.talbe1 TO read_only_user;
GRANT SELECT ON schema1.table2 TO read_only_user;

GRANT USAGE ON SCHEMA schema2 TO read_only_user;
GRANT SELECT ON schema2.talbe1 TO read_only_user;
GRANT SELECT ON schema2.table2 TO read_only_user;

(......and so on.....)

I just wonder if I could grant usage & privileges on future created schema in PostgreSQL. Could only find ways to alter default privileges on future created tables but not future created schemas.


回答1:


There are no default privileges for schemas. But since you are using a model whereby every user has its own schema you can automate the full process, including creating the user and setting a password, if needed:

CREATE FUNCTION new_user_schema (user text, pwd text) RETURNS void AS $$
DECLARE
  usr name;
  sch name;
BEGIN
  -- Create the user
  usr := quote_identifier(user);
  EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', usr, quote_literal(pwd));

  -- Create the schema named after the user and set default privileges
  sch := quote_identifier('sch_' || user);
  EXECUTE format('CREATE SCHEMA %I', sch);
  EXECUTE format('ALTER SCHEMA %I OWNER TO %L', sch, usr);
  EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I
                    GRANT SELECT ON TABLES TO %L', sch, usr);
END; $$ LANGUAGE plpgsql STRICT;

You can then create the user, create the schema and set up default privileges with a simple command:

SELECT new_user_schema('new_user', 'secret');


来源:https://stackoverflow.com/questions/31635662/grant-usage-privileges-on-future-created-schema-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!