首页 文章

授予PostgreSQL中未来创建的模式的使用和权限

提问于
浏览
6

我现在正在集成的应用程序将创建新的模式 . (每个客户都有自己的架构,例如schema1,schema2,schema3 ....等)为了授予对新创建的架构和架构中特定表的使用和只读访问权限,我执行以下命令:

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.....)

我只是想知道是否可以在PostgreSQL中为未来创建的模式授予使用权和特权 . 只能找到改变未来创建的表的默认权限的方法,而不是未来创建的模式 .

1 回答

  • 1

    模式没有默认权限 . 但是,由于您使用的模型中每个用户都有自己的架构,因此您可以自动完成整个过程,包括创建用户和设置密码(如果需要):

    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;
    

    然后,您可以使用简单命令创建用户,创建架构并设置默认权限:

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

相关问题