[英]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:所以我有这个 function 可以很好地更新产品的浏览次数:
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.不幸的是,由于这个 function 更新视图数量,这是不可能的,因为它是一个更新操作。
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?所以我想知道PSQL是否有任何方法允许我创建一个触发器function,每次查询数据时更新列值? 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
在products
上通过 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.并让 product_item() 执行UPDATE
,其中 product_item() 将设置SECURITY DEFINER
以便它可以作为特权用户运行。
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.我唯一能想到的就是创建一个 function,它是使用security definer
器作为对数据库具有写入权限的用户创建的。 Then the function is used instead of the table:然后使用 function 代替表:
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
如果您想允许查看多个产品,您可以将 function 更改为returns setof product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.