简体   繁体   中英

Increment value of a column field whenever SELECT row

So I have this function that works very nicely to update the count of views on a product:

UPDATE products SET view=view+1 WHERE id=@id RETURNING *

The problem is that I am currently switching my users to read-only to add more security. Unfortunately, as this function updates the number of view, it is not possible, since it is an update operation.

So I was wondering if there is any way that PSQL would allow me to create a trigger function that update column value each time data is queried? I looked at the official documentation but did not notice any example related to my usecase.

Perhaps something like this (pseudo-code):

CREATE TRIGGER view_increment
    AFTER SELECT ON products WHERE id=@id
    EXECUTE SET view=view+1;

The only thing I can think of is to have SELECT on products operate through a function:

SELECT * product_item(id);

And have product_item() do the UPDATE , where product_item() would have SECURITY DEFINER set so it can run as privileged user.

The only thing I can think of, is to create a function that is created with security definer as a user that has write privileges on the database. Then the function is used instead of the table:

create function get_product(p_product_id integer)
  returns products --<< returns a complete row
as
$$
  update products 
    set "view" = "view" + 1;
  select *
  from product
  where id = p_product_id;
$$
language sql
volatile
security definer; --<< runs with the privileges of the owner

Then the use it like this:

select *
from get_product(42);

If you want to allow to view multiple products you can change the function to returns setof product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM