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

时间:2015-07-26 09:54:27

标签: database postgresql privileges

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

String

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

1 个答案:

答案 0 :(得分: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');