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

edy*_*ang 6 database postgresql privileges

我现在正在集成的应用程序将创建新的模式.(每个客户都有自己的架构,例如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.....)
Run Code Online (Sandbox Code Playgroud)

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

Pat*_*ick 2

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

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;
Run Code Online (Sandbox Code Playgroud)

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

SELECT new_user_schema('new_user', 'secret');
Run Code Online (Sandbox Code Playgroud)