如何在PostgreSQL中锁定某些列以免被用户编辑

Har*_*mar 5 sql security postgresql locking postgresql-9.3

即使用户有权访问Postgresql中表的编辑权限,如何锁定某些列也不被编辑。

Nei*_*gan 7

PostgreSQL 支持列安全(以及行安全)

让我们称之为有限的角色 authors

create table staff (
  name text primary key,
  salary decimal(19,4)
);

create role authors;

grant select, insert, delete, update(name) on table staff to authors;

set role authors;

insert into staff values ('frank', 100); -- works!

select * from staff; -- works!

update staff set name='jim'; -- works!

update staff set salary=999; -- permission denied
Run Code Online (Sandbox Code Playgroud)


Lau*_*lbe 2

您可以添加一个触发器,如果​​禁止的列发生更改,则该触发器会抛出异常:

CREATE OR REPLACE FUNCTION cerberus() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   IF NEW.forbiddencol IS DISTINCT FROM OLD.forbiddencol
      AND current_user = 'luser'
   THEN
      RAISE EXCEPTION '"luser" must not update "forbiddencol"';
   END IF;
   RETURN NEW;
END;$$;

CREATE TRIGGER cerberus BEFORE UPDATE OF mytable
   FOR EACH ROW EXECUTE PROCEDURE cerberus();
Run Code Online (Sandbox Code Playgroud)