Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock certain columns from being edited for a user in postgresql

How to lock certain columns from being edited even though user have access to editing rights for the table in postgresql.

like image 791
Harnish Kumar Avatar asked Jun 01 '17 07:06

Harnish Kumar


People also ask

How do I lock a specific row in PostgreSQL?

Note that this will lock the entire table and referring to PostgreSQL there is no table level lock that can lock exclusively a specific row. row level lock in all your SELECT that will update your row and this will prevent all those SELECT that will update a row from reading your row !

How to lock columns in Excel Office 365?

How to Lock Column in Excel? To lock a column in Excel first we need to select the column which we need to Lock. Then click right anywhere on the selected column and select the Format Cells option from the right-click menu list. Now from the Protection tab of Format Cells, check the box of LOCKED with a tick.

What are PostgreSQL's lock modes?

PostgreSQL provides various lock modes to control concurrent access to data in tables. These modes can be used for application-controlled locking in situations where MVCC does not give the desired behavior.

What is PostgreSQL deadlock and how does it work?

PostgreSQL automatically detects deadlock situations and resolves them by aborting one of the transactions involved, allowing the other (s) to complete. (Exactly which transaction will be aborted is difficult to predict and should not be relied upon.)


2 Answers

PostgreSQL supports Column Security (as well as Row Security)

Let's call our limited role 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
like image 95
Neil McGuigan Avatar answered Nov 14 '22 21:11

Neil McGuigan


You can add a trigger that barfs if a forbidden column gets changed:

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();
like image 28
Laurenz Albe Avatar answered Nov 14 '22 22:11

Laurenz Albe