【问题标题】:PostgreSQL - Grant select on all tables (and future tables), in *all schemas*PostgreSQL - 在*所有模式*中授予对所有表(和未来表)的选择
【发布时间】:2018-03-19 18:43:52
【问题描述】:

我的数据库使用架构来分隔应用程序的特定于租户的数据 - 每个客户在注册时都会创建一个全新的架构来保存他们的数据。

这显然意味着我事先并不知道所有模式的名称。

我想创建一个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;

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

【问题讨论】:

    标签: sql postgresql schema


    【解决方案1】:

    你不能这样做,就像这里所说的那样: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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2022-12-11
      • 2014-05-06
      • 2010-09-16
      • 1970-01-01
      • 2019-01-07
      相关资源
      最近更新 更多