Deprecated Garbage Collections – Kenny Lee Chee Wei

A truckload of garbage by Kenny Lee Chee Wei

Archive for the ‘Postgres’ Category

Postgres – Grant privileges to all tables in a database

with 5 comments

Grant privileges to all tables in a database (select, update, insert, delete)

Eg:( Creating a read-only user in postgres)

For Postgres 8.*

For Postgres 7.*

–Function to grant access(select,insert,update,delete) to users

CREATE FUNCTION pg_grant(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS '
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (''r'',''v'',''S'') AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ''GRANT '' || $2 || '' ON '' || obj.relname || '' TO '' || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
' LANGUAGE plpgsql SECURITY DEFINER;

–Function to revoke access(select,insert,update,delete) from users

CREATE FUNCTION pg_revoke(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS '
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (''r'',''v'',''S'') AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ''REVOKE '' || $2 || '' ON '' || obj.relname || '' FROM '' || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
' LANGUAGE plpgsql SECURITY DEFINER;

–Create users for your database

CREATE USER userreadonly WITH PASSWORD 'userr3ad0nly';
CREATE USER userall WITH PASSWORD 'usersh0pa11';

–Grant respective access to users

select pg_grant('
userreadonly ','select','%','public');
select pg_grant('
userall ','select,insert,update,delete','%','public');

You might need to create lang for plpgsql if you had not done so

createlang plpgsql yrdatabasename

Advertisements

Written by kennii

September 21, 2007 at 2:50 am

Posted in Database, Postgres