PGsql:为模式上的用户授予每一项权限

时间:2011-07-23 08:31:06

标签: postgresql rights

我无法弄清楚如何为特定用户提供每一项权利,我希望用户在模式上拥有每一项权利:

  • 在现有表格上插入,删除,更新,选择......

我尝试过:

    GRANT ALL PRIVILEGES ON SCHEMA schema to "user";
    GRANT ALL ON SCHEMA schema to "local_518561";
    GRANT ALL PRIVILEGES ON table schema.table to "user";
    GRANT ALL ON table schema.table to "user";

查询返回成功,但每次我使用其他用户时我都会收到insuffiecent权限错误。

3 个答案:

答案 0 :(得分:20)

GRANT ALL PRIVILEGES ON                  SCHEMA schema_name TO role_name;
GRANT ALL PRIVILEGES ON ALL TABLES    IN SCHEMA schema_name TO role_name;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA schema_name TO role_name;

答案 1 :(得分:4)

如果您使用的是PostgreSQL版本< 9,您可以使用以下存储过程来管理表和序列的权限:

CREATE OR REPLACE FUNCTION grantTablesOfSchema (user VARCHAR,
   permissions VARCHAR, schema VARCHAR) RETURNS VARCHAR AS
$body$
DECLARE
  regActual   RECORD;
  numTables   INTEGER;
BEGIN

   numTables := 0;

   FOR regActual IN
      SELECT tablename FROM pg_tables WHERE schemaname = schema
   LOOP
      numTables := numTables + 1;

      EXECUTE 'GRANT ' || permissions || ' ON ' || schema || '.' || regActual.tablename || ' TO ' || user;
   END LOOP;

   RETURN 'Tables: ' || numTables::VARCHAR;
END;
$body$
LANGUAGE 'plpgsql';


CREATE OR REPLACE FUNCTION grantSequencesOfSchema (user VARCHAR,
   permissions VARCHAR, database VARCHAR, schema VARCHAR) RETURNS VARCHAR AS
$body$
DECLARE
   regActual       RECORD;
   numSequences    INTEGER;
BEGIN

   numSequences := 0;

   FOR regActual IN
      SELECT sequence_catalog, sequence_schema, sequence_name 
      FROM information_schema.sequences 
      WHERE sequence_catalog = database AND sequence_schema = schema
   LOOP
      numSequences := numSequences + 1;

      EXECUTE 'GRANT ' || permissions || ' ON ' || schema || '.' || regActual.sequence_name || ' TO ' || user;
   END LOOP;

   RETURN 'Sequences: ' || numSequences::VARCHAR;
END;
$body$
LANGUAGE 'plpgsql';

使用的一个例子:

CREATE USER user1 WITH PASSWORD 'user1@user1?user1';
GRANT CONNECT ON DATABASE database1 TO user1;
GRANT USAGE ON SCHEMA schema1 TO user1;

SELECT * FROM grantTablesOfSchema ('user1', 'SELECT, UPDATE, INSERT, DELETE', 'schema1');

SELECT * FROM grantSequencesOfSchema ('user1', 'ALL', 'database1', 'schema1');

相反,如果你的PostgreSQL版本是> = 9:

GRANT ALL ON ALL SEQUENCES IN SCHEMA schema1 TO user1;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA schema1 TO user1;

答案 2 :(得分:3)

答案在于序列,如果你没有赋予表格和序列(如果有的话)的权利而不能插入。