如果您使用的是版本的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 '[email protected]?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;