2017-10-08 39 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; 
相關問題