2017-10-08 36 views
2

我的数据库使用模式为应用程序分离特定于租户的数据 - 每个客户在注册时都会创建一个全新的模式数据。PostgreSQL - 授予所有表格(以及未来表格)的选择权,在*所有模式中*

这显然意味着我不知道所有模式的名称提前。

我想创建一个readonly角色,可以读取这些模式的所有以及将来创建的角色。

沿着这些线路的所有问题,我发现需要知道模式的名称,例如:

-- Create a group 
CREATE ROLE readaccess; 

-- Grant access to existing tables 
GRANT USAGE ON SCHEMA a_given_schema TO readaccess; 
GRANT SELECT ON ALL TABLES IN SCHEMA a_given_schema TO readaccess; 

-- Grant access to future tables 
ALTER DEFAULT PRIVILEGES IN SCHEMA a_given_schema GRANT SELECT ON TABLES TO readaccess; 

-- Create user with password 
CREATE USER readonly WITH PASSWORD 'a_secret'; 
GRANT readaccess TO readonly; 

有没有办法做这样的事情,但在未来的所有模式?

回答

0

你不能做的是,这里说:grant usage & privileges on future created schema in PostgreSQL

最好是想别的办法:每次创建模式时,您授予在同一时间的作用:(看看链接了解更多信息)

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; 
相关问题